var isDebugMode = false;
var debugMode = 0;
var debugConsoleEntry;
var debugConsoleEntryCopyHidden;
var debugConsoleOutput;
var debugConsoleEntryHistory = [];
var debugConsoleEntryHistoryOffset = 0;
var debugConsoleEntryIntellisenseBox;
var debugConsoleEntryIntellisenseList;
var debugConsoleEntryIntellisenseListItemSelectedIndex = 0;
var debugConsoleIntellisenseRequestId = 0;
var debugConsoleEntryIntellisenseBoxSignature;
var CompletionKindText = 1;
var CompletionKindMethod = 2;
var CompletionKindFunction = 3;
var CompletionKindConstructor = 4;
var CompletionKindField = 5;
var CompletionKindVariable = 6;
var CompletionKindClass = 7;
var CompletionKindInterface = 8;
var CompletionKindModule = 9;
var CompletionKindProperty = 10;
var CompletionKindUnit = 11;
var CompletionKindValue = 12;
var CompletionKindEnum = 13;
var CompletionKindKeyword = 14;
var CompletionKindSnippet = 15;
var CompletionKindColor = 16;
var CompletionKindFile = 17;
var CompletionKindReference = 18;
var CompletionKindFolder = 19;
var CompletionKindEnumMember = 20;
var CompletionKindConstant = 21;
var CompletionKindStruct = 22;
var CompletionKindEvent = 23;
var CompletionKindOperator = 24;
var CompletionKindTypeParameter = 25;
var CompletionKindGotoTarget = 26;
var CompletionKindEventNoParams = 27;
var CompletionKindInfo = 28;
var CompletionKindEnumSuggestedPrefix = 29;
var debugConsoleEntryContainer;
var totalTimeTaken = 0;
var debugConsoleContent;
var debugConsolePartialLineItem = undefined;
var debugConsolePartialLineItem_LastColorClass = undefined;
var debugPanelOptions = { showTimestamps: true, invertDirection: false };
function GetJsTimeStamp() {
  var e = new Date();
  var t = e.getHours();
  if (t < 10) t = "0" + t;
  var o = e.getMinutes();
  if (o < 10) o = "0" + o;
  var n = e.getSeconds();
  if (n < 10) n = "0" + n;
  var i = e.getMilliseconds();
  if (i < 10) {
    i = "00" + i;
  } else if (i < 100) {
    i = "0" + i;
  }
  return t + ":" + o + ":" + n + "." + i;
}
function initDebugConsolePanel() {}
function clearDebugConsole() {
  debugConsoleOutput.contentDiv.clear();
}
function toggleDebugOutputDirection(e) {
  debugPanelOptions.invertDirection = debugPanelOptions.invertDirection
    ? false
    : true;
  if (debugPanelOptions.invertDirection) {
    e.iconClassDiv.classList.add("tickIcon");
    e.iconClassDiv.classList.remove("noTickIcon");
  } else {
    e.iconClassDiv.classList.remove("tickIcon");
    e.iconClassDiv.classList.add("noTickIcon");
  }
  resyncDebugPanelOptions();
}
function toggleDebugShowTimestamps(e) {
  debugPanelOptions.showTimestamps = debugPanelOptions.showTimestamps
    ? false
    : true;
  if (debugPanelOptions.showTimestamps) {
    e.iconClassDiv.classList.add("tickIcon");
    e.iconClassDiv.classList.remove("noTickIcon");
  } else {
    e.iconClassDiv.classList.remove("tickIcon");
    e.iconClassDiv.classList.add("noTickIcon");
  }
  resyncDebugPanelOptions();
}
function resyncDebugPanelOptions() {
  if (debugPanelOptions.showTimestamps === undefined) {
    debugPanelOptions.showTimestamps = true;
  }
  if (debugPanelOptions.showTimestamps) {
    document.documentElement.style.setProperty(
      "--timestampsDisplay",
      "inline-block"
    );
  } else {
    document.documentElement.style.setProperty("--timestampsDisplay", "none");
  }
  debugConsoleContent.setInvertMode(debugPanelOptions.invertDirection);
}
function createDebugConsole(e) {
  if (debugConsoleOutput) return debugConsoleOutput;
  var t = {};
  t.sectionExpander = createDOMElement(
    undefined,
    "div",
    "panelHeaderIconLeft sectionExpanderIcon"
  );
  t.panelDiv = e;
  t.sectionHeaderInner = createDOMElement(
    undefined,
    "div",
    "sectionHeaderInner",
    "调试控制台"
  );
  t.sectionRoot = createDOMElement(undefined, "div", "sectionRoot");
  t.sectionBody = createDOMElement(t.sectionRoot, "div", "sectionBody");
  var o = createDOMElement(t.sectionBody, "div", "debugConsoleOuter");
  debugConsoleOutput = createDOMElement(o, "div", "debugConsoleOutput2");
  debugConsoleContent = createListView(debugConsoleOutput);
  debugConsoleContent.setShowScrollbarV(true);
  debugConsoleContent.setShowScrollbarH(false);
  debugConsoleContent.setAutoScroll(true);
  debugConsoleContent.setAutoScrollAutoLock(true);
  debugConsoleContent.setAutoScrollAutoUnlock(true);
  debugConsoleEntryContainer = createDOMElement(
    o,
    "div",
    "debugConsoleEntryContainer"
  );
  var n = createDOMElement(
    debugConsoleEntryContainer,
    "div",
    "debugConsoleEntryMarker",
    ">"
  );
  debugConsoleEntry = createDOMElement(
    debugConsoleEntryContainer,
    "input",
    "debugConsoleEntry"
  );
  debugConsoleEntryCopyHidden = createDOMElement(
    document.body,
    "div",
    "debugConsoleEntry debugConsoleEntryCopyHidden"
  );
  debugConsoleEntryIntellisenseBox = createDOMElement(
    document.body,
    "div",
    "debugConsoleEntryIntellisenseBox"
  );
  debugConsoleEntryIntellisenseBoxSignature = createDOMElement(
    document.body,
    "div",
    "debugConsoleEntryIntellisenseBoxSignature"
  );
  debugConsoleEntryIntellisenseBoxSignature.onmousedown = sigHelpClick;
  debugConsoleEntryIntellisenseBoxSignature.tabIndex = "0";
  debugConsoleEntryIntellisenseBoxSignature.onblur =
    onDebugConsoleEntryLostFocus;
  debugConsoleEntryIntellisenseList = createVirtualListView(
    debugConsoleEntryIntellisenseBox
  );
  debugConsoleEntryIntellisenseList.setShowScrollbarH(false);
  debugConsoleEntryIntellisenseList.onFinishedRender = () => {
    if (debugConsoleEntryIntellisenseList.pendingLazyCompletions.length) {
      lspSocket.request(
        "textDocument/lazyCompletion",
        {
          lazyRequestId: debugConsoleEntryIntellisenseList.lazyRequestId,
          requests: debugConsoleEntryIntellisenseList.pendingLazyCompletions,
        },
        (e) => {
          if (e.results) {
            e.results.forEach((e) => {
              var t = debugConsoleEntryIntellisenseList.dataNodesDATA[e.x];
              for (const o in e) {
                if (o !== "x") {
                  if (Object.hasOwn(e, o)) {
                    t[o] = e[o];
                  }
                }
              }
              t.gotData = true;
              debugConsoleEntryIntellisenseList.notifyChangedItem(e.x);
            });
          }
        }
      );
    }
    debugConsoleEntryIntellisenseList.pendingLazyCompletions = [];
  };
  debugConsoleEntryIntellisenseList.onAsyncGetItemHTML = (e) => {
    var t = debugConsoleEntryIntellisenseList.dataNodesDATA[e];
    var o = t.l;
    var n = undefined;
    if (t.gotData) {
      n = t.type;
    } else if (t.requestedData) {
      n = "...";
    } else if (t.i) {
      t.requestedData = true;
      debugConsoleEntryIntellisenseList.pendingLazyCompletions.push({
        x: e,
        i: t.i,
      });
      n = "...";
    }
    if (!o) o = "";
    if (!n) n = "";
    o = TEXTtoHTML(o);
    n = TEXTtoHTML(n);
    if (debugConsoleEntryIntellisenseList.currentWord.length > 0)
      o = replaceCaseInsensitive(
        o,
        debugConsoleEntryIntellisenseList.currentWord,
        "<span class='isensePartialHilite'>###</span>"
      );
    var i = undefined;
    var r = undefined;
    var s = "";
    switch (t.t) {
      case CompletionKindMethod:
        {
          i = "symbol-method";
          r = "";
        }
        break;
      case CompletionKindFunction:
        {
          i = "symbol-function";
          r = n ? "returns " : "";
          s = "<div class='isenseTypeFunction'>(...)</div>";
        }
        break;
      case CompletionKindConstructor:
        {
          i = "symbol-method";
          r = "";
        }
        break;
      case CompletionKindField:
        {
          i = "symbol-field";
          r = "field";
        }
        break;
      case CompletionKindVariable:
        {
          i = "symbol-variable";
          r = "variable";
        }
        break;
      case CompletionKindClass:
        {
          i = "symbol-class";
          r = "class";
        }
        break;
      case CompletionKindInterface:
        {
          i = "symbol-interface";
          r = "interface";
        }
        break;
      case CompletionKindModule:
        {
          i = "symbol-module";
          r = "module";
        }
        break;
      case CompletionKindProperty:
        {
          i = "symbol-property";
          r = "property";
        }
        break;
      case CompletionKindEnum:
        {
          i = "symbol-enum";
          r = "enum";
        }
        break;
      case CompletionKindKeyword:
        {
          i = "symbol-keyword";
          r = "";
        }
        break;
      case CompletionKindReference:
        {
          i = "symbol-reference";
          r = "reference";
        }
        break;
      case CompletionKindFolder:
        {
          i = "symbol-package";
          r = "library";
          s = ".";
        }
        break;
      case CompletionKindEnumMember:
        {
          i = "symbol-enum-member";
          r = "enum-value";
        }
        break;
      case CompletionKindConstant:
        {
          i = "symbol-constant";
          r = "constant";
        }
        break;
      case CompletionKindStruct:
        {
          i = "symbol-structure";
          r = "user defined type";
        }
        break;
      case CompletionKindEvent:
        {
          i = "symbol-event";
          r = "";
          s = "<div class='isenseTypeFunction'>(...)</div>";
        }
        break;
      case CompletionKindEventNoParams:
        {
          i = "symbol-event";
          r = "";
        }
        break;
      case CompletionKindOperator:
        {
          i = "symbol-keyword";
          r = "";
        }
        break;
      case CompletionKindGotoTarget:
        {
          i = "target";
          r = "";
        }
        break;
      case CompletionKindInfo:
        {
          i = "info";
          r = "";
        }
        break;
      case CompletionKindEnumSuggestedPrefix:
        {
          i = "symbol-enum";
          r = "enum";
          s = ".";
        }
        break;
      default: {
        debugger;
        i = "circle-small";
      }
    }
    if (t.aliasType) {
      r = "alias";
      n = t.aliasType;
    }
    var a = r ? "<span class='isenseSubtype'>" + r + "</span>" : "";
    if (t.isDefault) {
      return (
        "<div class='isenseOuter isenseOuterDefault'><div class='codicon codicon-" +
        i +
        "'></div><div class='isenseLabel'>" +
        o +
        "</div>" +
        s +
        "<div class='isenseType'>" +
        a +
        n +
        "</div>"
      );
    } else if (t.isSelected) {
      return (
        "<div class='isenseOuter isenseOuterSelected'><div class='codicon codicon-" +
        i +
        "'></div><div class='isenseLabel'>" +
        o +
        "</div>" +
        s +
        "<div class='isenseType'>" +
        a +
        n +
        "</div>"
      );
    } else {
      return (
        "<div class='isenseOuter'><div class='codicon codicon-" +
        i +
        "'></div><div class='isenseLabel'>" +
        o +
        "</div>" +
        s +
        "<div class='isenseType'>" +
        a +
        n +
        "</div>"
      );
    }
  };
  debugConsoleEntry.spellcheck = false;
  debugConsoleEntry.autocomplete = false;
  debugConsoleEntry.onkeydown = onDebugConsoleEntryKeyDown;
  debugConsoleEntry.onkeypress = onDebugConsoleEntryKeyPress;
  debugConsoleEntry.onkeyup = onDebugConsoleEntryKeyUp;
  debugConsoleEntry.onblur = onDebugConsoleEntryLostFocus;
  t.friendlyName = "调试控制台";
  assignToPanel(t, undefined, t.panelDiv);
  t.sectionHeader.sectionRoot = t.sectionRoot;
  if (t.sectionHeader.restoreCustomSize) t.sectionHeader.restoreCustomSize();
  t.sectionHeader.panelId = "debug-console";
  var i = createDOMElement(
    t.sectionHeader,
    "div",
    "panelHeaderIcon arrowDownWithBar panelToggleButtonOn"
  );
  i.onclick = (e) => {
    e.stopPropagation();
    if (i.classList.contains("panelToggleButtonOn")) {
      i.classList.remove("panelToggleButtonOn");
      debugConsoleContent.setAutoScroll(false);
      debugConsoleContent.setAutoScrollAutoLock(false);
    } else {
      i.classList.add("panelToggleButtonOn");
      debugConsoleContent.setAutoScroll(true);
      debugConsoleContent.setAutoScrollAutoLock(true);
    }
  };
  i.title = "自动滚动";
  debugConsoleContent.onautoscrollchanged = (e) => {
    var t = i.classList.contains("panelToggleButtonOn");
    var o = debugConsoleContent.autoScroll;
    if (t != o) {
      if (o) {
        i.classList.add("panelToggleButtonOn");
      } else {
        i.classList.remove("panelToggleButtonOn");
      }
    }
  };
  var r = createDOMElement(
    t.sectionHeader,
    "div",
    "panelHeaderIcon clearScreenIcon"
  );
  r.onclick = (e) => {
    clearDebugConsole();
    e.stopPropagation();
  };
  r.title = "清空控制台";
  var s = createDOMElement(
    t.sectionHeader,
    "div",
    "panelHeaderIcon ellipsesIcon"
  );
  s.onclick = (e) => {
    showContextMenu(undefined, e.clientX, e.clientY, [
      {
        id: "debugOutputDirection",
        name: "反转输出方向",
        action: (e) => toggleDebugOutputDirection(e),
        iconClass: debugPanelOptions.invertDirection
          ? "tickIcon"
          : "noTickIcon",
      },
      {
        id: "debugShowTimestamp",
        name: "显示时间戳",
        action: (e) => toggleDebugShowTimestamps(e),
        iconClass: debugPanelOptions.showTimestamps ? "tickIcon" : "noTickIcon",
      },
    ]);
    e.stopPropagation();
  };
}
function debugOutputLine(e, t, o, n) {
  if (e.length == 0) {
    e = " ";
  }
  if (debugConsolePartialLineItem) {
    var i = debugConsoleContent.onAsyncGetItemHTML(debugConsolePartialLineItem);
    debugConsoleContent.updateItem(debugConsolePartialLineItem, i + "</span>");
    debugConsolePartialLineItem = undefined;
  }
  let r = "<span class='ts'>";
  if (n) {
    r += n;
  } else {
    r += GetJsTimeStamp();
  }
  debugConsoleContent.addItem(
    "<span class='" +
      t +
      "'>" +
      r +
      "</span>" +
      (o ? e : TEXTtoHTML(e)) +
      "</span>"
  );
}
function debugOutputPartial(e, t, o, n) {
  var i = e.substr(e.length - 2, 2) === "\r\n";
  if (i) {
    e = e.substr(0, e.length - 2);
  }
  if (debugConsolePartialLineItem) {
    let n = debugConsoleContent.onAsyncGetItemHTML(debugConsolePartialLineItem);
    if (debugConsolePartialLineItem_LastColorClass === t) {
      e = TEXTtoHTML(e);
    } else {
      e = "</span><span class='" + t + "'>" + (o ? e : TEXTtoHTML(e));
    }
    var r = o ? e : TEXTtoHTML(e);
    debugConsoleContent.updateItem(debugConsolePartialLineItem, n + r);
  } else {
    let i = "<span class='ts'>";
    if (n) {
      i += n;
    } else {
      i += GetJsTimeStamp();
    }
    debugConsolePartialLineItem = debugConsoleContent.addItem(
      "<span class='" + t + "'>" + i + "</span>" + (o ? e : TEXTtoHTML(e))
    );
  }
  if (i) {
    let e = debugConsoleContent.onAsyncGetItemHTML(debugConsolePartialLineItem);
    debugConsoleContent.updateItem(debugConsolePartialLineItem, e + "</span>");
    debugConsolePartialLineItem = undefined;
  }
  debugConsolePartialLineItem_LastColorClass = t;
}
function handleIsenseUpKey() {
  if (debugConsoleEntryIntellisenseList.dataNodesDATA[0].isDefault) {
    debugConsoleEntryIntellisenseList.dataNodesDATA[0].isDefault = false;
    debugConsoleEntryIntellisenseList.notifyChangedItem(0);
  }
  if (debugConsoleEntryIntellisenseListItemSelectedIndex >= 0) {
    debugConsoleEntryIntellisenseList.dataNodesDATA[
      debugConsoleEntryIntellisenseListItemSelectedIndex
    ].isSelected = false;
    debugConsoleEntryIntellisenseList.notifyChangedItem(
      debugConsoleEntryIntellisenseListItemSelectedIndex
    );
  }
  debugConsoleEntryIntellisenseListItemSelectedIndex--;
  if (debugConsoleEntryIntellisenseListItemSelectedIndex < 0) {
    debugConsoleEntryIntellisenseListItemSelectedIndex =
      debugConsoleEntryIntellisenseList.itemCount - 1;
  }
  if (debugConsoleEntryIntellisenseListItemSelectedIndex >= 0) {
    debugConsoleEntryIntellisenseList.dataNodesDATA[
      debugConsoleEntryIntellisenseListItemSelectedIndex
    ].isSelected = true;
    debugConsoleEntryIntellisenseList.notifyChangedItem(
      debugConsoleEntryIntellisenseListItemSelectedIndex
    );
    debugConsoleEntryIntellisenseList.ensureVisible(
      debugConsoleEntryIntellisenseListItemSelectedIndex
    );
  }
}
function handleIsenseDownKey() {
  if (debugConsoleEntryIntellisenseList.dataNodesDATA[0].isDefault) {
    debugConsoleEntryIntellisenseList.dataNodesDATA[0].isDefault = false;
    debugConsoleEntryIntellisenseList.notifyChangedItem(0);
  }
  if (debugConsoleEntryIntellisenseListItemSelectedIndex >= 0) {
    debugConsoleEntryIntellisenseList.dataNodesDATA[
      debugConsoleEntryIntellisenseListItemSelectedIndex
    ].isSelected = false;
    debugConsoleEntryIntellisenseList.notifyChangedItem(
      debugConsoleEntryIntellisenseListItemSelectedIndex
    );
  }
  debugConsoleEntryIntellisenseListItemSelectedIndex++;
  if (
    debugConsoleEntryIntellisenseListItemSelectedIndex ==
    debugConsoleEntryIntellisenseList.itemCount
  ) {
    debugConsoleEntryIntellisenseListItemSelectedIndex = 0;
  }
  if (
    debugConsoleEntryIntellisenseListItemSelectedIndex <
    debugConsoleEntryIntellisenseList.itemCount
  ) {
    debugConsoleEntryIntellisenseList.dataNodesDATA[
      debugConsoleEntryIntellisenseListItemSelectedIndex
    ].isSelected = true;
    debugConsoleEntryIntellisenseList.notifyChangedItem(
      debugConsoleEntryIntellisenseListItemSelectedIndex
    );
    debugConsoleEntryIntellisenseList.ensureVisible(
      debugConsoleEntryIntellisenseListItemSelectedIndex
    );
  }
}
function onDebugConsoleEntryKeyDown(e) {
  let t = debugConsoleEntryIntellisenseBox.style.display === "block";
  if (e.key === "Tab") {
    e.preventDefault();
    return;
  }
  if (e.key === "ArrowUp") {
    if (t) {
      handleIsenseUpKey();
      e.stopPropagation();
      return false;
    } else {
      if (debugConsoleEntryHistoryOffset >= debugConsoleEntryHistory.length)
        return false;
      let e =
        debugConsoleEntryHistory[
          debugConsoleEntryHistory.length - ++debugConsoleEntryHistoryOffset
        ];
      debugConsoleEntry.value = e;
      debugConsoleEntry.setSelectionRange(999999999, 999999999);
      return false;
    }
  } else if (e.key === "ArrowDown") {
    if (t) {
      handleIsenseDownKey();
      e.stopPropagation();
      return false;
    } else {
      if (debugConsoleEntryHistoryOffset <= 1) return false;
      let e =
        debugConsoleEntryHistory[
          debugConsoleEntryHistory.length - --debugConsoleEntryHistoryOffset
        ];
      debugConsoleEntry.value = e;
      debugConsoleEntry.setSelectionRange(999999999, 999999999);
      return false;
    }
  } else if (e.code === "Space") {
    if (t) {
      if (debugConsoleEntryIntellisenseListItemSelectedIndex !== -1) {
        handleSelectedDebugConsoleIntellisenseEntry(
          debugConsoleEntryIntellisenseListItemSelectedIndex
        );
      }
    }
  }
}
function onDebugConsoleEntryKeyPress(e) {
  debugConsoleEntryHistoryOffset = 0;
  let t = debugConsoleEntryIntellisenseBox.style.display === "block";
  if (
    e.key === "Enter" &&
    (!t || debugConsoleEntryIntellisenseListItemSelectedIndex === -1)
  ) {
    debugOutputLine(debugConsoleEntry.value, "debugConsoleEvaluateEnteredText");
    if (!debugSocket.isConnected) {
      debugOutputLine(
        "ERROR: DEBUGGER IS NOT CONNECTED.",
        "debugConsoleErrorText"
      );
      return;
    }
    var o = debugConsoleEntryHistory.length
      ? debugConsoleEntryHistory[debugConsoleEntryHistory.length - 1]
      : "";
    if (o !== debugConsoleEntry.value && debugConsoleEntry.value.length > 0) {
      debugConsoleEntryHistory.push(debugConsoleEntry.value);
    }
    var n = { expression: debugConsoleEntry.value };
    if (activeDebuggingFrameId) n.frameId = activeDebuggingFrameId;
    debugSocket.request("evaluate", n, (e) => {
      if (e.message)
        debugOutputLine(e.message, "debugConsoleEvaluateResultText");
      if (!e.success) {
        if (e.message == "aborted") clearDebuggingCallframe();
      }
    });
    debugConsoleEntry.value = "";
  }
}
function getLiveDebugIntellisense(e, t, o) {
  let n = e.expr;
  var i = "";
  let r = e.caret - 1;
  let s = r;
  while (s >= 0) {
    var a = n.charAt(s);
    if (
      a === "." ||
      a === "," ||
      a === " " ||
      a === "\t" ||
      a === "!" ||
      a === "?" ||
      a === "+" ||
      a === "-" ||
      a === "*" ||
      a === "/" ||
      a === "\\" ||
      a === "^" ||
      a === "&" ||
      a === "(" ||
      a === "=" ||
      a === "[" ||
      a === ":"
    ) {
      break;
    }
    s--;
  }
  e.caret = s + 1;
  var l = n.charAt(r);
  if (s !== r) {
    s++;
    i = n.substr(s, r + 1 - s);
  }
  var d = {
    text: n,
    column: e.caret + 1,
    line: 1,
    wordLength: i.length,
    context: l ? { triggerCharacter: l } : {},
  };
  if (activeDebuggingFrameId) d.frameId = activeDebuggingFrameId;
  i = i.toLowerCase();
  debugSocket.request("completions", d, (o) => {
    if (!o.body) o.body = {};
    if (!o.body.targets) o.body.targets = [];
    if (i.length > 0) {
      o.body.targets = o.body.targets.filter(
        (e) => e.l.toLowerCase().indexOf(i) == 0
      );
    }
    function n(e, t) {
      if (e.p === t.p) {
        return e.l.localeCompare(t.l, "en", { sensitivity: "base" });
      }
      var o = e.p ? e.p : 0;
      var n = t.p ? t.p : 0;
      if (o < n) return -1;
      return 1;
    }
    o.body.targets.sort(n);
    t(i, e.caret, o.body.targets, o.body.signatures, o.body.lazyRequestId);
  });
}
function getLiveDebugIntellisenseMonaco(e, t, o, n, i) {
  let r = e.lineNumber;
  let s = e.caret;
  let a = e.expr;
  var l = "";
  let d = e.caret - 2;
  let c = d;
  while (c >= 0) {
    var u = a.charAt(c);
    if (
      u === "." ||
      u === "," ||
      u === " " ||
      u === "\t" ||
      u === "!" ||
      u === "?" ||
      u === "+" ||
      u === "-" ||
      u === "*" ||
      u === "/" ||
      u === "\\" ||
      u === "^" ||
      u === "&" ||
      u === "(" ||
      u === "=" ||
      u === "[" ||
      u === ":"
    ) {
      break;
    }
    c--;
  }
  var p = a.charAt(d);
  if (o) p = "";
  e.caret = c + 1;
  if (c !== d) {
    c++;
    l = a.substr(c, d + 1 - c);
  }
  l = l.toLowerCase();
  if (t && l.length === 0) {
    debugConsoleEntryIntellisenseBox.style.display = "none";
    debugConsoleEntryIntellisenseBoxSignature.style.display = "none";
    return;
  }
  var f = openEditors.selectedEditorNode.fileNode.getFullPath();
  lspSocket.request(
    "textDocument/completion",
    {
      textDocument: {
        uri: f,
        version: openEditors.selectedEditorNode.fileNode.ideVersionId,
      },
      position: { line: e.lineNumber - 1, character: e.caret },
      context: p ? { triggerCharacter: p } : {},
      origCaretLine: r,
      origCaretColumn: s,
    },
    (t) => {
      t.body = {};
      t.body.targets = t.result.items;
      if (l.length > 0) {
        t.body.targets = t.body.targets.filter(
          (e) => e.l.toLowerCase().indexOf(l) == 0
        );
      }
      function o(e, t) {
        if (e.p === t.p) {
          return e.l.localeCompare(t.l, "en", { sensitivity: "base" });
        }
        var o = e.p ? e.p : 0;
        var n = t.p ? t.p : 0;
        if (o < n) return -1;
        return 1;
      }
      t.body.targets.sort(o);
      n(
        l,
        e.caret,
        t.body.targets,
        t.result.signatures,
        t.result.lazyRequestId
      );
    }
  );
}
function handleSelectedDebugConsoleIntellisenseEntry(e, t) {
  var o = debugConsoleEntryIntellisenseList.dataNodesDATA[e];
  debugConsoleEntryIntellisenseBox.style.display = "none";
  if (o.t == CompletionKindInfo) return;
  var n = o.l;
  var i = debugConsoleEntry.value;
  var r = debugConsoleEntryIntellisenseList.currentWord;
  var s = debugConsoleEntryIntellisenseList.currentCaretPos;
  if (n.charAt(0) == "_") n = "[" + n + "]";
  var a = 0;
  if (o.t == CompletionKindFunction || o.t == CompletionKindEvent) {
    n += "()";
    a += -1;
  }
  var l = i.substr(0, s) + n + i.substr(s + r.length);
  debugConsoleEntry.value = l;
  if (t) a += 1;
  debugConsoleEntry.selectionStart = s + n.length + a;
  {
    debugConsoleEntry.selectionEnd = s + n.length + a;
  }
  let d = document.body.getBoundingClientRect();
  let c = debugConsoleEntryContainer.getBoundingClientRect();
  debugConsoleEntryIntellisenseBoxSignature.style.bottom =
    d.height - (c.top - 1) + "px";
  if (a) {
    onDebugConsoleEntryKeyUp({});
  }
}
function onDebugConsoleEntryLostFocus(e) {
  setTimeout(() => {
    if (!isClickOnSigHelpToggle) {
      debugConsoleEntryIntellisenseBox.style.display = "none";
      debugConsoleEntryIntellisenseBoxSignature.style.display = "none";
    }
  }, 100);
}
function replaceCaseInsensitive(e, t, o) {
  let n = e.toLowerCase().indexOf(t.toLowerCase());
  if (n === -1) return e;
  var i = e.substring(n, t.length);
  o = o.replace("###", i);
  e = e.substring(0, n) + o + e.substring(n + t.length);
  return e;
}
function onDebugConsoleEntryKeyUp(e) {
  var t = e.key;
  let o = debugConsoleEntryIntellisenseBox.style.display === "block";
  if (o) {
    if (e.key === "Escape" || e.key === "ArrowLeft" || e.key === "ArrowRight") {
      debugConsoleEntryIntellisenseBox.style.display = "none";
      debugConsoleEntryIntellisenseBoxSignature.style.display = "none";
      e.stopPropagation();
      return false;
    } else if (e.key === "ArrowUp") {
      return;
    } else if (e.key === "ArrowDown") {
      return;
    } else if (e.key === "Tab") {
      if (debugConsoleEntryIntellisenseListItemSelectedIndex !== -1) {
        handleSelectedDebugConsoleIntellisenseEntry(
          debugConsoleEntryIntellisenseListItemSelectedIndex
        );
        e.stopPropagation();
        return false;
      } else {
        handleSelectedDebugConsoleIntellisenseEntry(0);
        e.stopPropagation();
        return false;
      }
    } else if (e.key === "Enter") {
      if (debugConsoleEntryIntellisenseListItemSelectedIndex !== -1) {
        handleSelectedDebugConsoleIntellisenseEntry(
          debugConsoleEntryIntellisenseListItemSelectedIndex
        );
        e.stopPropagation();
        return false;
      }
    }
    if (debugConsoleEntryIntellisenseListItemSelectedIndex !== -1) {
      if (SpecialKeysThatAcceptSelectedIntellisense[t]) {
        handleSelectedDebugConsoleIntellisenseEntry(
          debugConsoleEntryIntellisenseListItemSelectedIndex,
          t
        );
        return;
      }
    }
  } else {
    let t = debugConsoleEntryIntellisenseBoxSignature.style.display === "block";
    if (t) {
      if (
        e.key === "Escape" ||
        e.key === "Enter" ||
        e.key === "ArrowUp" ||
        e.key === "ArrowDown"
      ) {
        debugConsoleEntryIntellisenseBoxSignature.style.display = "none";
        e.stopPropagation();
        return;
      }
    }
  }
  if (
    e.key === "ArrowUp" ||
    e.key === "ArrowDown" ||
    e.key === "ArrowLeft" ||
    e.key === "ArrowRight" ||
    e.key === "Escape" ||
    e.key === "Shift" ||
    e.key === "Control" ||
    e.key === "Alt"
  ) {
    return;
  }
  if (e.ctrlKey && e.key == " ") {
  } else {
    if (liveIDEOptions["intellisenseMode"] !== "MODERN") {
      if (liveIDEOptions["intellisenseMode"] === "LEGACY") {
        if (!o && !LegacyKeysThatTriggerIntellisense[e.key]) {
          return;
        }
      } else {
        let e =
          debugConsoleEntryIntellisenseBoxSignature.style.display === "block";
        if (!o && !e) {
          return;
        }
      }
    }
  }
  debugConsoleIntellisenseRequestId++;
  let n = debugConsoleIntellisenseRequestId;
  debugConsoleEntryIntellisenseList.onHeightTooLarge = (e) => {
    if (n == debugConsoleIntellisenseRequestId) {
      let t = debugConsoleEntryContainer.getBoundingClientRect();
      debugConsoleEntryIntellisenseBox.style.top = t.top - e + 1 + "px";
      debugConsoleEntryIntellisenseBox.style.height = e + "px";
      debugConsoleEntryIntellisenseList.setShowScrollbarV(false);
      let o = document.body.getBoundingClientRect();
      debugConsoleEntryIntellisenseBoxSignature.style.bottom =
        o.height - (t.top - e - 1) + "px";
    }
  };
  debugConsoleEntryIntellisenseList.onClickItem = (e) => {
    handleSelectedDebugConsoleIntellisenseEntry(e.index);
  };
  getLiveDebugIntellisense(
    { expr: debugConsoleEntry.value, caret: debugConsoleEntry.selectionStart },
    (e, t, o, i, r) => {
      if (n !== debugConsoleIntellisenseRequestId) {
        return;
      }
      debugConsoleEntryIntellisenseListItemSelectedIndex = -1;
      debugConsoleEntryCopyHidden.innerText = debugConsoleEntry.value.substr(
        0,
        t
      );
      let s = debugConsoleEntryCopyHidden.getBoundingClientRect().width;
      debugConsoleEntryIntellisenseBox.style.height = "200px";
      debugConsoleEntryIntellisenseList.setShowScrollbarV(true);
      debugConsoleEntryIntellisenseList.setItemCount(0);
      debugConsoleEntryIntellisenseList.resetScrollPosition();
      debugConsoleEntryIntellisenseList.lazyRequestId = r;
      debugConsoleEntryIntellisenseList.pendingLazyCompletions = [];
      debugConsoleEntryIntellisenseList.currentWord = e;
      debugConsoleEntryIntellisenseList.currentCaretPos = t;
      if (o.length == 0) {
        debugConsoleEntryIntellisenseBox.style.display = "none";
      } else {
        if (o.length > 0) {
          o[0].isDefault = true;
          if (o[0].l.localeCompare(e, "en", { sensitivity: "base" }) === 0)
            o[0].isExactMatch = true;
        }
        debugConsoleEntryIntellisenseList.setItemCount(o.length);
        debugConsoleEntryIntellisenseList.dataNodesDATA = o;
        debugConsoleEntryIntellisenseBox.style.left = "-500px";
        debugConsoleEntryIntellisenseBox.style.display = "block";
      }
      let a = debugConsoleEntry.getBoundingClientRect();
      let l = debugConsoleEntryIntellisenseBox.getBoundingClientRect();
      let d = debugConsoleEntryContainer.getBoundingClientRect();
      debugConsoleEntryIntellisenseBox.style.left =
        a.left - debugConsoleEntry.scrollLeft + s + "px";
      debugConsoleEntryIntellisenseBox.style.top = d.top - l.height + 1 + "px";
      if (i && i.length) {
        let e = document.body.getBoundingClientRect();
        debugConsoleEntryIntellisenseBoxSignature.style.left =
          a.left - debugConsoleEntry.scrollLeft + s + "px";
        debugConsoleEntryIntellisenseBoxSignature.style.bottom =
          e.height - (d.top - l.height - 1) + "px";
        debugConsoleEntryIntellisenseBoxSignature.style.display = "block";
        debugConsoleEntryIntellisenseBoxSignature.innerText = "";
        debugConsoleEntryIntellisenseBoxSignature.classList.add("noBoxShadow");
        var c = "";
        i.forEach((e) => {
          var t = e.label;
          if (e.activeParam > 0 && e.activeParam <= e.params.length) {
            let o = e.params[e.activeParam - 1].label[0];
            let n = e.params[e.activeParam - 1].label[1];
            t =
              TEXTtoHTML(t.substr(0, o)) +
              "<div class='debugSigHelpActiveArg'>" +
              TEXTtoHTML(t.substr(o, n - o)) +
              "</div>" +
              TEXTtoHTML(t.substr(n));
          } else {
            t = TEXTtoHTML(t);
          }
          if (c.length) c += "<br/>";
          c += "<div class='sigHelpHeaderText'>" + t + "</div>";
        });
        debugConsoleEntryIntellisenseBoxSignature.innerHTML +=
          "<div class='sigHelpHeader'><div class='sigHelpHeaderFoldIcon codicon " +
          (sigHelpIsExpanded ? "codicon-fold-down" : "codicon-fold-up") +
          "' onclick='toggleSigHelp()' title='Fold/Collapse (F1)'></div><div class='sigHelpHeaderTextOuter'>" +
          c +
          "</div></div>";
        let t = i[0];
        var u = window.markdownit();
        var p = u.render(t.doc);
        var f = t.doc.split("\r\n");
        var g = 0;
        var m = f[g++];
        while (g < f.length && (m.charAt(0) === "#" || m.trim().length == 0)) {
          m = f[g++];
        }
        if (m.indexOf("```") === 0) {
          while (g < f.length) {
            var h = f[g++];
            m += "\r\n" + h;
            if (h.indexOf("```") === 0) break;
          }
        }
        if (m) {
          var v = u.render(m);
          currentSigHelpExpandedHtml = p;
          currentSigHelpCollapsedHtml = v;
          if (sigHelpIsExpanded) v = p;
          debugConsoleEntryIntellisenseBoxSignature.innerHTML +=
            "<div class='sigHelpText'>" + v + "</div>";
        }
      } else {
        debugConsoleEntryIntellisenseBoxSignature.style.display = "none";
      }
    },
    n
  );
}
var toolWindowUniqueId = 0;
var toolWindows_ALL = [];
var g_timeBefore = 0;
var g_timeAfter = 0;
async function loadToolWindowsFromPersistanceData(e) {
  var t = 0;
  while (t < e.length) {
    var o = e[t++];
    if (o.type === "问题") {
      await createToolWindowPROBLEMS(
        o.WindowLeft,
        o.WindowTop,
        o.WindowWidth,
        o.WindowHeight
      );
    } else if (o.type === "大纲") {
      await createToolWindowOUTLINE(
        o.WindowLeft,
        o.WindowTop,
        o.WindowWidth,
        o.WindowHeight
      );
    }
  }
}
function closeAllToolWindows() {
  toolWindows_ALL.forEach((e) => {
    e.WindowClosed = true;
    hostAppObject.PostMessageToToolWindow(e.commsID, "X");
  });
}
function minimizeAllToolWIndows() {
  toolWindows_ALL.forEach((e) => {
    hostAppObject.PostMessageToToolWindow(e.commsID, "M");
  });
}
function restoreAllToolWIndows() {
  toolWindows_ALL.forEach((e) => {
    hostAppObject.PostMessageToToolWindow(e.commsID, "R");
  });
}
function getToolWindowsPersistanceData() {
  var e = [];
  toolWindows_ALL.forEach((t) => {
    if (!t.WindowClosed) {
      e.push({
        type: t.type,
        WindowLeft: t.WindowLeft,
        WindowTop: t.WindowTop,
        WindowWidth: t.WindowWidth,
        WindowHeight: t.WindowHeight,
      });
    }
  });
  return e;
}
async function createToolWindowPROBLEMS(e, t, o, n) {
  var i = createToolWindowComms(toolWindowUniqueId, problemsPanel, "问题");
  problemsPanel.tree.associatedToolWindows.push(i);
  toolWindows_ALL.push(i);
  if (!e && !t && !o && !n) {
    e = undefined;
    t = undefined;
    o = undefined;
    n = undefined;
  }
  var r = {
    type: "init",
    msg: "问题",
    toolWindowID: toolWindowUniqueId,
    colorTheme: liveIDEOptions["colorTheme"],
  };
  if (e !== undefined) {
    r.Left = e;
    i.WindowLeft = e;
  }
  if (t !== undefined) {
    r.Top = t;
    i.WindowTop = t;
  }
  if (o !== undefined) {
    r.Width = o;
    i.WindowWidth = o;
  }
  if (n !== undefined) {
    r.Height = n;
    i.WindowHeight = n;
  }
  r.AAStart = 0;
  r.ZZEnd = 0;
  toolWindowUniqueId++;
  await hostAppObject.CreateToolWindow(JSON.stringify(r));
  return i;
}
async function createToolWindowOUTLINE(e, t, o, n) {
  var i = createToolWindowComms(toolWindowUniqueId, outlinePanel, "大纲");
  outlinePanel.tree.associatedToolWindows.push(i);
  toolWindows_ALL.push(i);
  if (!e && !t && !o && !n) {
    e = undefined;
    t = undefined;
    o = undefined;
    n = undefined;
  }
  var r = {
    type: "init",
    msg: "大纲",
    toolWindowID: toolWindowUniqueId,
    colorTheme: liveIDEOptions["colorTheme"],
  };
  if (e !== undefined) {
    r.Left = e;
    i.WindowLeft = e;
  }
  if (t !== undefined) {
    r.Top = t;
    i.WindowTop = t;
  }
  if (o !== undefined) {
    r.Width = o;
    i.WindowWidth = o;
  }
  if (n !== undefined) {
    r.Height = n;
    i.WindowHeight = n;
  }
  r.AAStart = 0;
  r.ZZEnd = 0;
  toolWindowUniqueId++;
  await hostAppObject.CreateToolWindow(JSON.stringify(r));
  return i;
}
function createToolWindowComms(e, t, o) {
  return {
    commsID: e,
    realPanel: t,
    pendingMessages: [],
    type: o,
    WindowLeft: 0,
    WindowTop: 0,
    WindowWidth: 0,
    WindowHeight: 0,
    WindowClosed: false,
    postMessageObject(e) {
      if (this.pendingMessages === undefined) {
        hostAppObject.PostMessageToToolWindow(this.commsID, JSON.stringify(e));
      } else {
        this.pendingMessages.push(e);
      }
    },
    gotMessageObject(e) {
      if (this.pendingMessages === undefined) {
        if (e.type === "getNodesUISnapshot") {
          var o = {
            type: "getNodesUISnapshotResponse",
            data: t.tree.getNodesUISnapshot(e.visibleIndex, e.requestCount),
            requestID: e.requestID,
          };
          hostAppObject.PostMessageToToolWindow(
            this.commsID,
            JSON.stringify(o)
          );
        } else if (e.type === "clickedNode") {
          t.tree.view.onClickNode(e.visibleIndex);
        } else if (e.type === "rightClickedNode") {
          t.tree.view.onRightClickNode(e.visibleIndex, e.clientX, e.clientY);
        } else if (e.type === "dblClickedNode") {
          t.tree.view.onDblClickNode(e.visibleIndex);
        } else if (e.type === "toggleExpanded") {
          t.tree.view.toggleExpanded(e.visibleIndex);
        } else if (e.type === "toolWindowPositionChanged") {
          this.WindowLeft = e.WindowLeft;
          this.WindowTop = e.WindowTop;
          this.WindowWidth = e.WindowWidth;
          this.WindowHeight = e.WindowHeight;
          this.WindowClosed = e.WindowClosed;
        } else {
        }
      } else {
        var n = this.pendingMessages;
        this.pendingMessages = undefined;
        n.forEach((e) => {
          this.postMessageObject(e);
        });
      }
    },
  };
}
function handleToolWindowMessage(e) {
  toolWindows_ALL[e.toolWindowID].gotMessageObject(e);
}
var contextMenu;
var contextMenuSUB;
var currentSelectedTopMenu;
var currentMenuDescriptor;
var currentSubMenuDescriptor;
var currentFocusedMenuItem;
var preservedFocusedMainMenuItem;
var subMenuRefCount = 0;
function initContextMenu() {
  contextMenu = document.getElementById("contextMenu");
  contextMenuSUB = document.getElementById("contextMenuSUB");
  contextMenu.tabIndex = "0";
  contextMenu.onkeydown = (e) => {
    if (e.key === "Escape") {
      hideContextMenu();
    }
  };
  contextMenuSUB.onkeydown = (e) => {
    if (e.key === "Escape") {
      hideContextMenuSub();
    }
  };
}
function SubMenuAddRef() {
  subMenuRefCount++;
}
function SubMenuRelease() {
  setTimeout(() => {
    subMenuRefCount--;
    if (subMenuRefCount == 0) {
      hideContextMenuSub();
    }
  }, 0);
}
function setFocusedMenuItem(e) {
  if (currentFocusedMenuItem !== undefined) {
    currentFocusedMenuItem.domObject.classList.remove("focusedMenuItem");
  }
  e.domObject.classList.add("focusedMenuItem");
  currentFocusedMenuItem = e;
}
function hideContextMenuSub() {
  contextMenuSUB.innerHTML = "";
  contextMenuSUB.style.visibility = "hidden";
  currentSubMenuDescriptor = undefined;
  unselectFocusedMenuItem();
}
function unselectFocusedMenuItem() {
  if (currentFocusedMenuItem) {
    currentFocusedMenuItem.domObject.classList.remove("focusedMenuItem");
    currentFocusedMenuItem = undefined;
  }
}
function hideContextMenu() {
  hideContextMenuSub();
  contextMenu.innerHTML = "";
  contextMenu.style.visibility = "hidden";
  currentMenuDescriptor = undefined;
  currentSubMenuDescriptor = undefined;
  unselectFocusedMenuItem();
  unlockUI();
  if (currentSelectedTopMenu) {
    currentSelectedTopMenu.classList.remove("isMenuItemSelected");
    currentSelectedTopMenu = undefined;
  }
}
function onHoverMenuItem(e) {
  if (e.hoverAction) {
    e.hoverAction(e.domObject);
  }
  unselectFocusedMenuItem();
}
function onUnhoverMenuItem(e) {
  if (e.unhoverAction) {
    e.unhoverAction(e.domObject);
  }
  unselectFocusedMenuItem();
}
function showContextSubMenu(e, t, o) {
  unselectFocusedMenuItem();
  subMenuRefCount = 1;
  contextMenuSUB.innerHTML = "";
  contextMenuSUB.style.visibility = "hidden";
  currentSubMenuDescriptor = o;
  o.forEach((e) => {
    {
      if (e.name) {
        e.domObject = createDOMElement(
          contextMenuSUB,
          "div",
          "contextMenuItem",
          e.name
        );
        if (e.detail) {
          createDOMElement(
            e.domObject,
            "div",
            "contextMenuItemDetail",
            e.detail
          );
        }
        if (e.iconClass) {
          e.iconClassDiv = createDOMElement(
            e.domObject,
            "div",
            "contextMenuItemIcon " + e.iconClass
          );
        }
        if (e.isHidden) {
          e.domObject.classList.add("contextMenuItemDisabled");
        } else {
          e.domObject.onmouseup = () => {
            if (e.action(e)) return;
            hideContextMenu();
          };
          e.domObject.onmouseenter = () => onHoverMenuItem(e);
          e.domObject.onmouseleave = () => onUnhoverMenuItem(e);
        }
      } else {
        e.domObject = createDOMElement(contextMenuSUB, "hr");
      }
    }
  });
  contextMenuSUB.style.left = "0px";
  contextMenuSUB.style.top = "0px";
  var n = contextMenuSUB.clientWidth;
  contextMenuSUB.style.visibility = "visible";
  contextMenuSUB.style.left = e + "px";
  contextMenuSUB.style.top = t + "px";
  if (contextMenuSUB.clientHeight + t > document.body.clientHeight - 5) {
    contextMenuSUB.style.top =
      document.body.clientHeight - 5 - contextMenuSUB.clientHeight + "px";
  }
  if (contextMenuSUB.clientWidth + e > document.body.clientWidth - 5) {
    contextMenuSUB.style.left = document.body.clientWidth - 5 - n + "px";
  }
  contextMenuSUB.onmouseenter = SubMenuAddRef;
  contextMenuSUB.onmouseleave = SubMenuRelease;
}
function showContextMenu(e, t, o, n, i, r) {
  unselectFocusedMenuItem();
  if (!e && contextMenu.style.visibility === "visible") {
    showContextSubMenu(t, o, n);
    return;
  }
  preservedFocusedMainMenuItem = undefined;
  if (e && currentSelectedTopMenu === e) {
    hideContextMenu();
    return;
  } else if (e && currentSelectedTopMenu !== e) {
    hideContextMenuSub();
  }
  subMenuRefCount = 0;
  hideTooltipNow();
  contextMenu.innerHTML = "";
  contextMenu.style.visibility = "hidden";
  if (currentSelectedTopMenu) {
    currentSelectedTopMenu.classList.remove("isMenuItemSelected");
    currentSelectedTopMenu = undefined;
    unlockUI();
  }
  if (e) {
    currentSelectedTopMenu = e;
    currentSelectedTopMenu.classList.add("isMenuItemSelected");
    lockUI(rootMenuFile.offsetHeight + "px", hideContextMenu);
  } else {
    lockUI(0, hideContextMenu);
  }
  currentMenuDescriptor = n;
  n.forEach((e) => {
    {
      if (e.name) {
        e.domObject = createDOMElement(
          contextMenu,
          "div",
          "contextMenuItem",
          e.name
        );
        if (e.detail) {
          createDOMElement(
            e.domObject,
            "div",
            "contextMenuItemDetail",
            e.detail
          );
        }
        if (e.iconClass) {
          e.iconClassDiv = createDOMElement(
            e.domObject,
            "div",
            "contextMenuItemIcon " + e.iconClass
          );
        }
        if (e.isHidden) {
          e.domObject.classList.add("contextMenuItemDisabled");
        } else {
          e.domObject.onmouseup = () => {
            if (e.action(e)) return;
            hideContextMenu();
          };
          if (e.hoverAction) {
            e.domObject.onmouseenter = () => {
              e.hoverAction(e.domObject);
            };
          }
          if (e.unhoverAction) {
            e.domObject.onmouseleave = () => {
              e.unhoverAction();
            };
          }
        }
      } else {
        e.domObject = createDOMElement(contextMenu, "hr");
      }
    }
  });
  contextMenu.style.left = "0px";
  contextMenu.style.top = "0px";
  var s = contextMenu.clientWidth;
  contextMenu.style.visibility = "visible";
  contextMenu.style.left = t + "px";
  contextMenu.style.top = o + "px";
  if (contextMenu.clientHeight + o > document.body.clientHeight - 5) {
    contextMenu.style.top =
      document.body.clientHeight - 5 - contextMenu.clientHeight + "px";
  }
  if (s + t > document.body.clientWidth - 5) {
    contextMenu.style.left = document.body.clientWidth - 5 - s + "px";
  }
  contextMenu.style.minWidth = "0px";
  if (i) {
    contextMenu.style.minWidth = i + "px";
  }
  if (r) {
    contextMenu.style.top = o - contextMenu.offsetHeight + "px";
  }
  contextMenu.focus();
}
var callStackPanel;
function initCallStackPanel() {}
function stackFrameRenderNode(e) {
  var t = createDOMElement(e.innerDiv, "div", "stackFrameProc");
  var o = createDOMElement(e.innerDiv, "div", "stackFrameFile");
  var n = createDOMElement(e.innerDiv, "div", "stackFrameLineCol");
  var i = e.customRenderData;
  t.innerText = i.name;
  o.innerText = i.source.path.split("/").pop();
  n.innerText = i.line + ":" + i.column;
}
function onStackFrameClick(e, t) {
  setDebuggingCallframe(
    t.threadId,
    t.customRenderData,
    undefined,
    undefined,
    undefined,
    true
  );
}
function onStackFrameDblClick(e, t) {
  setDebuggingCallframe(
    t.threadId,
    t.customRenderData,
    undefined,
    undefined,
    undefined,
    false
  );
}
class _CallStackPanel {
  constructor(e) {
    this.tree = new treeView(e, "调用栈", "callstack:", false, 5, true);
    this.tree.render();
    this.selectedEditorNode = undefined;
    this.tree.showFolderIcons = false;
    this.tree.onClickItem = onStackFrameClick;
    this.tree.onDblClickItem = onStackFrameDblClick;
    this.tree.needsFlexNodes = true;
  }
  gotThreadInfo(e, t) {
    var o = e.toString();
    var n = this.tree.rootFolder.entries[o];
    if (!n) {
      n = this.tree.rootFolder.addFolder(o, t, true);
      n.sort = false;
    } else {
      n.displayName = t;
      n.render();
    }
  }
  gotCallstackInfo(e, t) {
    doLayoutChanges(() => {
      var o = e.toString();
      var n = this.tree.rootFolder.entries[o];
      if (!n) {
        n = this.tree.rootFolder.addFolder(o, "THREADID_" + e, true);
        n.sort = false;
        debugSocket.updateThreadInfo(e);
      }
      n.clear();
      if (t && t.body && t.body.stackFrames) {
        var i = 0;
        var r = t.body.stackFrames.length;
        n.muteRendering = true;
        t.body.stackFrames.forEach((t) => {
          t.isTopFrame = i == 0;
          var o = n.addItemCustom(
            t.id,
            stackFrameRenderNode,
            t,
            i == 0 ? "yellowArrowRight" : "noIcon2"
          );
          o.threadId = e;
          i++;
        });
        n.muteRendering = false;
        n.renderEntries();
        if (e === activeDebuggingThreadId) {
          variablesPanel.syncVariablesPanelToStackFrame(t.body.stackFrames[0]);
        }
      }
    });
  }
  clearCallstackInfo(e) {
    callStackPanel.gotCallstackInfo(e, undefined);
  }
}
function createCallStackPanel(e) {
  if (callStackPanel) return callStackPanel;
  callStackPanel = new _CallStackPanel(e);
}
var codePanelDropDownContainer = undefined;
var codePanelDropDownComponent = undefined;
var codePanelDropDownScope = undefined;
var codePanelDropDownProcedure = undefined;
var codeComboSelectors = undefined;
var nextScopeUpdateIsAnEdit = undefined;
var currentComponentFormDesignerId = undefined;
var currentScope = undefined;
var currentScopeName = undefined;
function createDropDowns() {
  codePanelDropDownContainer = createDOMElement(
    codePanel,
    "div",
    "codePanelDropDownContainer hideNotCodeEditor"
  );
  codePanelDropDownComponent = createDOMElement(
    codePanelDropDownContainer,
    "select",
    "dropDown codePanelDropDownComponent"
  );
  createDOMElement(codePanelDropDownComponent, "option", "", "(component)");
  createDOMElement(codePanelDropDownComponent, "option", "", "");
  createDOMElement(codePanelDropDownComponent, "option", "", "");
  createDOMElement(codePanelDropDownComponent, "option", "", "");
  createDOMElement(codePanelDropDownComponent, "option", "", "");
  createDOMElement(codePanelDropDownComponent, "option", "", "");
  codePanelDropDownComponent.onmousedown = populateComponentsCombo;
  codePanelDropDownComponent.onchange = changedComponentsCombo;
  codePanelDropDownScope = createDOMElement(
    codePanelDropDownContainer,
    "select",
    "dropDown codePanelDropDownScope"
  );
  createDOMElement(codePanelDropDownScope, "option", "", "(general)");
  createDOMElement(codePanelDropDownScope, "option", "", "");
  createDOMElement(codePanelDropDownScope, "option", "", "");
  createDOMElement(codePanelDropDownScope, "option", "", "");
  createDOMElement(codePanelDropDownScope, "option", "", "");
  createDOMElement(codePanelDropDownScope, "option", "", "");
  codePanelDropDownScope.onmousedown = populateScopesCombo;
  codePanelDropDownScope.onchange = changedScopesCombo;
  codePanelDropDownProcedure = createDOMElement(
    codePanelDropDownContainer,
    "select",
    "dropDown codePanelDropDownProcedure"
  );
  createDOMElement(codePanelDropDownProcedure, "option", "", "(declaration)");
  createDOMElement(codePanelDropDownProcedure, "option", "", "");
  createDOMElement(codePanelDropDownProcedure, "option", "", "");
  createDOMElement(codePanelDropDownProcedure, "option", "", "");
  createDOMElement(codePanelDropDownProcedure, "option", "", "");
  createDOMElement(codePanelDropDownProcedure, "option", "", "");
  codePanelDropDownProcedure.onmousedown = populateProceduresCombo;
  codePanelDropDownProcedure.onchange = changedProceduresCombo;
  codeComboSelectors = new _CodeComboSelectors();
}
function populateComponentsCombo(e) {
  if (e.detail === 0) return;
  var t = codeComboSelectors.cachedScopes;
  codePanelDropDownComponent.innerHTML = "";
  {
    doLayoutChanges(() => {
      var e = createDOMElement(
        codePanelDropDownComponent,
        "option",
        "",
        "(component)"
      );
      e.hidden = true;
      const o = [...t].sort((e, t) =>
        e.name.toLowerCase() < t.name.toLowerCase()
          ? -1
          : e.name.toLowerCase() > t.name.toLowerCase()
          ? 1
          : 0
      );
      o.forEach((e) => {
        var t = createDOMElement(
          codePanelDropDownComponent,
          "option",
          "",
          e.name
        );
        t.lineStart = e.range.start.line;
        t.lineStartPos = e.range.start.character;
      });
    });
  }
}
function changedComponentsCombo(e) {
  var t =
    codePanelDropDownComponent.options[
      codePanelDropDownComponent.selectedIndex
    ];
  revealLineInEditor(t.lineStart + 1, t.lineStartPos + 1);
  editor.focus();
}
var temp = 0;
function populateScopesCombo(e) {
  if (e.detail === 0) return;
  codePanelDropDownScope.innerHTML = "";
  {
    doLayoutChanges(() => {
      var e = createDOMElement(codePanelDropDownScope, "option", "", "");
      e.hidden = true;
      e = createDOMElement(codePanelDropDownScope, "option", "", "(general)");
      currentScope.procedures.forEach((t) => {
        if (!t.scopeEventName) {
          if (e.firstPreExistingMethod === undefined) {
            e.firstPreExistingMethod = {
              procInfoLine: t.range.start.line,
              procInfoLinePos: t.range.start.character,
            };
          }
        }
      });
      const t = [...currentScope.children].sort((e, t) =>
        e.name.toLowerCase() < t.name.toLowerCase()
          ? -1
          : e.name.toLowerCase() > t.name.toLowerCase()
          ? 1
          : 0
      );
      t.forEach((e) => {
        var t = createDOMElement(codePanelDropDownScope, "option", "", e.name);
        e.members.forEach((e) => {
          if (e.procName) {
            if (e.isDefault || t.firstPreExistingMethod === undefined) {
              t.firstPreExistingMethod = e;
            }
          }
          if (e.isDefault || t.defaultMethod === undefined) {
            t.defaultMethod = e;
          }
        });
      });
    });
  }
}
function changedScopesCombo() {
  var e = codePanelDropDownScope.options[codePanelDropDownScope.selectedIndex];
  var t = e.firstPreExistingMethod ? e.firstPreExistingMethod : e.defaultMethod;
  if (t.procInfo) {
    var o = new monaco.Range(
      t.procInfoLine + 1,
      t.procInfoLinePos + 1,
      t.procInfoLine + 1,
      t.procInfoLinePos + 1
    );
    revealedLineTime = undefined;
    editor.setSelection(o);
    let e = editor.getContribution("snippetController2");
    e.insert(t.procInfo);
  } else {
    revealLineInEditor(t.procInfoLine + 1, t.procInfoLinePos + 1);
  }
  editor.focus();
}
function populateProceduresCombo(e) {
  if (e.detail === 0) return;
  codePanelDropDownProcedure.innerHTML = "";
  {
    doLayoutChanges(() => {
      var e = createDOMElement(
        codePanelDropDownProcedure,
        "option",
        "",
        "(declaration)"
      );
      e.hidden = true;
      if (currentScopeName) {
        const e = [...currentScope.children].sort((e, t) =>
          e.name.toLowerCase() < t.name.toLowerCase()
            ? -1
            : e.name.toLowerCase() > t.name.toLowerCase()
            ? 1
            : 0
        );
        e.forEach((e) => {
          if (e.name === currentScopeName) {
            const t = [...e.members].sort((e, t) =>
              e.name.toLowerCase() < t.name.toLowerCase()
                ? -1
                : e.name.toLowerCase() > t.name.toLowerCase()
                ? 1
                : 0
            );
            t.forEach((e) => {
              var t = createDOMElement(
                codePanelDropDownProcedure,
                "option",
                e.procName ? "bold" : "",
                e.name + (e.procName ? " [" + e.procName + "]" : "")
              );
              t.procInfo = e.procInfo;
              t.procInfoLine = e.procInfoLine;
              t.procInfoLinePos = e.procInfoLinePos;
            });
          }
        });
      } else {
        const e = [...currentScope.procedures].sort((e, t) =>
          e.name.toLowerCase() < t.name.toLowerCase()
            ? -1
            : e.name.toLowerCase() > t.name.toLowerCase()
            ? 1
            : 0
        );
        e.forEach((e) => {
          if (!e.scopeEventName) {
            var t = createDOMElement(
              codePanelDropDownProcedure,
              "option",
              "",
              e.name + (e.detail ? " " + e.detail : "")
            );
            t.procInfoLine = e.range.start.line;
            t.procInfoLinePos = e.range.start.character;
          }
        });
      }
    });
  }
}
function changedProceduresCombo(e) {
  var t =
    codePanelDropDownProcedure.options[
      codePanelDropDownProcedure.selectedIndex
    ];
  if (t.procInfo) {
    var o = new monaco.Range(
      t.procInfoLine + 1,
      t.procInfoLinePos + 1,
      t.procInfoLine + 1,
      t.procInfoLinePos + 1
    );
    revealedLineTime = undefined;
    editor.setSelection(o);
    let e = editor.getContribution("snippetController2");
    e.insert(t.procInfo);
  } else {
    revealLineInEditor(t.procInfoLine + 1, t.procInfoLinePos + 1);
  }
  editor.focus();
}
function getShortTime(e) {
  var t = e.getHours();
  var o = e.getMinutes();
  return (t < 10 ? "0" : "") + t + ":" + (o < 10 ? "0" : "") + o;
}
class _CodeComboSelectors {
  constructor() {}
  changedDocumentPosition(e) {
    this.cachedLinePosition = e;
    e -= 1;
    codePanelDropDownComponent.innerHTML = "";
    codePanelDropDownScope.innerHTML = "";
    codePanelDropDownProcedure.innerHTML = "";
    var t = undefined;
    currentComponentFormDesignerId = undefined;
    currentScopeName = undefined;
    var o = undefined;
    if (this.cachedScopes) {
      this.cachedScopes.forEach((n) => {
        if (e >= n.range.start.line && e <= n.range.end.line) {
          t = n.name;
          currentComponentFormDesignerId = n.formDesignerId;
          currentScope = n;
          n.procedures.forEach((t) => {
            if (e >= t.range.start.line && e <= t.range.end.line) {
              currentScopeName = t.scopeName;
              if (t.scopeEventName) {
                o = t.scopeEventName + " [" + t.name + "]";
              } else {
                o = t.name;
              }
            }
          });
        }
      });
    }
    createDOMElement(
      codePanelDropDownComponent,
      "option",
      "",
      t ? t : "(component)"
    );
    createDOMElement(codePanelDropDownComponent, "option", "", "");
    createDOMElement(codePanelDropDownComponent, "option", "", "");
    createDOMElement(codePanelDropDownComponent, "option", "", "");
    createDOMElement(codePanelDropDownComponent, "option", "", "");
    createDOMElement(codePanelDropDownComponent, "option", "", "");
    createDOMElement(
      codePanelDropDownScope,
      "option",
      "",
      currentScopeName ? currentScopeName : "(general)"
    );
    createDOMElement(codePanelDropDownScope, "option", "", "");
    createDOMElement(codePanelDropDownScope, "option", "", "");
    createDOMElement(codePanelDropDownScope, "option", "", "");
    createDOMElement(codePanelDropDownScope, "option", "", "");
    createDOMElement(codePanelDropDownScope, "option", "", "");
    createDOMElement(
      codePanelDropDownProcedure,
      "option",
      "",
      o ? o : "(declaration)"
    );
    createDOMElement(codePanelDropDownProcedure, "option", "", "");
    createDOMElement(codePanelDropDownProcedure, "option", "", "");
    createDOMElement(codePanelDropDownProcedure, "option", "", "");
    createDOMElement(codePanelDropDownProcedure, "option", "", "");
    createDOMElement(codePanelDropDownProcedure, "option", "", "");
    if (nextScopeUpdateIsAnEdit) {
      nextScopeUpdateIsAnEdit = false;
      updateHistoryBookmarks();
      var n = openEditors.selectedEditorNode.fileNode.getFullPath();
      var i = [];
      if (t) i.push(t);
      if (currentScopeName) i.push(currentScopeName);
      if (o) i.push(o.split("[")[0].trim());
      var r = i.join(".");
      updateHistory(n, r, e + 1);
    }
  }
  syncScopes(e) {
    this.cachedScopes = e;
    this.changedDocumentPosition(this.cachedLinePosition);
  }
}
("use strict");
var buildTable = [
  {
    id: "configuration.inherits",
    friendly: "配置: 继承自",
    description:
      "此配置继承自的配置名称。此配置文件中的任何未设置属性将从此基配置文件继承。",
    values: "{inherits}",
    runtimeUpdateValues(e) {
      var t = "Defaults";
      configManager.buildConfigurationData.buildConfigurations.forEach((o) => {
        if (o["configuration.name"] !== e) {
          t += "," + o["configuration.name"];
        }
      });
      this.values = t;
    },
    validate(e) {
      if (e === undefined || e.length == 0) {
        return `value must be specified.  use 'Defaults' instead of a blank string here.`;
      } else if (!this.values.split(",").includes(e)) {
        return `[${e}] is not a valid configuration name in this workspace`;
      }
      return true;
    },
  },
  {
    id: "compiler.target",
    friendly: "编译: 目标",
    description:
      "编译器生成代码的目标体系结构。",
    values: "win32,win64",
    validate(e) {
      if (e !== "" && e !== "win32" && e !== "win64") {
        return `invalid value`;
      }
      return true;
    },
  },
  {
    id: "compiler.autoRestart",
    friendly: "编译: 自动重启编译器在崩溃",
    description:
      "如果是，编译器将在崩溃时自动启动。",
    values: "{bool}",
  },
  {
    id: "debugger.optionExplicit",
    friendly: "调试器: 强制显式(Option Explicit On)",
    description: "此选项影响调试控制台中输入的代码",
    values: "{bool}",
  },
  {
    id: "debugger.stackedBreakpoints",
    friendly: "调试器: 堆叠断点",
    description:
      "如果是，调试器将返回到断点，如果在调试器中执行代码，该代码会触发更深的断点",
    values: "{bool}",
  },
  {
    id: "debugger.fullRefreshOnSetVariable",
    friendly: "调试器: 强制刷新变量",
    description:
      "如果是，调试器将在更改变量值时刷新所有变量和监视表达式",
    values: "{bool}",
  },
  {
    id: "debugger.preferEarlyBoundInterfaces",
    friendly: "调试器: 优先使用早期绑定接口",
    description:
      "如果是，调试器将在标记为双接口的 dispinterface 上切换和绑定到 vtable 接口",
    values: "{bool}",
  },
  {
    id: "debugger.sortLocalsAlphabetically",
    friendly: "调试器: 按字母顺序排序局部变量",
    description:
      "如果是，调试器将按字母顺序对本地变量进行排序。如果否，它们将按声明的顺序出现。",
    values: "{bool}",
  },
  {
    id: "debugger.sortUDTsAlphabetically",
    friendly: "调试器: 按字母顺序排序用户定义类型",
    description:
      "如果是，调试器将按字母顺序对用户定义类型成员进行排序。如果否，它们将按声明的顺序出现。",
    values: "{bool}",
  },
  {
    id: "debugger.sortFieldsAlphabetically",
    friendly: "调试器: 按字母顺序排序字段",
    description:
      "如果是，调试器将按字母顺序对类字段成员进行排序。如果否，它们将按声明的顺序出现。",
    values: "{bool}",
  },
  {
    id: "debugger.showUDTPadding",
    friendly: "调试器: 显示用户定义类型填充",
    description:
      "If YES, the debugger will show any padding members that the compiler has added to UDTs.  Only applicable when [调试器: 按字母顺序排序字段] is NO",
    values: "{bool}",
  },
  {
    id: "debugger.showHexValues",
    friendly: "调试器: 显示十六进制值",
    description:
      "如果是，调试器将在十六进制形式中显示非十进制数值",
    values: "{bool}",
  },
  {
    id: "debugger.showHiddenMembers",
    friendly: "调试器: 显示隐藏成员",
    description:
      "如果是，调试器将隐藏标记为隐藏或不可浏览的成员",
    values: "{bool}",
  },
  {
    id: "debugger.showObjectPointerValues",
    friendly: "调试器: 显示对象指针值",
    description:
      "如果是，调试器将显示对象指针的原始值（即对象存储的原始内存位置）",
    values: "{bool}",
  },
  {
    id: "debugger.consoleLogTimeTaken",
    friendly: "调试器: 控制台日志时间消耗",
    description:
      "如果是，调试器将在结果下方的行代码执行所需的时间",
    values: "{bool}",
  },
  {
    id: "debugger.runtimeCommandLineArguments",
    friendly: "调试器: 运行时命令行参数",
    description:
      "在这里输入的文本将在运行时调试会话中通过VBA.Interaction.Command$函数可用",
    values: "{text}",
  },
  {
    id: "intellisense.showHiddenMembers",
    friendly: "智能感知: 显示隐藏成员",
    description:
      "如果是，智能感知将显示标记为隐藏或不可浏览的成员",
    values: "{bool}",
  },
  {
    id: "intellisense.showEventInterfaces",
    friendly: "智能感知: 显示事件接口",
    description:
      "如果是，智能感知将显示确定为事件源接口的接口",
    values: "{bool}",
  },
  {
    id: "intellisense.showDefaultInheritedInterfaces",
    friendly: "智能感知: 显示默认继承的接口",
    description:
      "如果是，智能感知将显示确定为类默认接口的接口",
    values: "{bool}",
  },
  {
    id: "intellisense.hideLeadingUnderscoreElements",
    friendly: "智能感知: 隐藏前导下划线元素",
    description:
      "如果是，智能感知将隐藏以下划线开头的接口和成员",
    values: "{bool}",
  },
  {
    id: "ide.compilerPortNumber",
    friendly: "IDE: 编译器网络端口号",
    description:
      "如果为0，则使用随机可用端口号",
    values: "{int}",
    validate(e) {
      if (e < 0) return "value must be >= 0";
      if (e > 65535) return "value must be <= 65535";
      return true;
    },
  },
  {
    id: "ide.fsPortNumber",
    friendly: "IDE: 文件系统网络端口号",
    description:
      "如果为0，则使用随机可用端口号",
    values: "{int}",
    validate(e) {
      if (e < 0) return "value must be >= 0";
      if (e > 65535) return "value must be <= 65535";
      return true;
    },
  },
  {
    id: "ide.dapPortNumber",
    friendly: "IDE: 调试器网络端口号",
    description:
      "如果为0，则使用随机可用端口号",
    values: "{int}",
    validate(e) {
      if (e < 0) return "value must be >= 0";
      if (e > 65535) return "value must be <= 65535";
      return true;
    },
  },
  {
    id: "ide.lspPortNumber",
    friendly: "IDE: 语言服务器网络端口号",
    description:
      "如果为0，则使用随机可用端口号",
    values: "{int}",
    validate(e) {
      if (e < 0) return "value must be >= 0";
      if (e > 65535) return "value must be <= 65535";
      return true;
    },
  },
  {
    id: "compilation.disabled",
    friendly: "编译: 禁用",
    description:
      "如果设置为YES，则不会调用编译器。使用此作为最后的手段打开项目文件，例如，如果存在阻止项目打开的显著编译器错误。",
    values: "{bool}",
  },
];
function buildTableUpdate(e) {
  buildTable.forEach((t) => {
    if (t.runtimeUpdateValues !== undefined) {
      t.runtimeUpdateValues(e);
    }
  });
}
var projectTable = [
  {
    id: "project.name",
    friendly: "项目: 名称",
    description:
      "这是用于表示项目的命名空间符号，如果生成了类型库，则为类型库名称",
    values: "{text}",
    validate(e) {
      var t = /[ `!@#$£%^&*()+\-=\[\]{};':"\\|,.<>\/?~]/;
      if (t.test(e)) return "value contains illegal characters";
      if (e && e.toString().indexOf("_") == 0)
        return "value contains illegal characters";
      return true;
    },
  },
  {
    id: "project.description",
    friendly: "项目: 描述",
    description:
      "如果生成了类型库，则为类型库描述。  您可以在这里包含编译器变量，例如${Architecture}, ${VersionMajor}, ${VersionMinor}, ${VersionBuild}, ${VersionRevision}",
    values: "{text}",
  },
  {
    id: "project.appTitle",
    friendly: "项目: 应用程序标题",
    description:
      "这是用于MsgBox和InputBox的默认标题标题，并且也用于App.Title属性返回的值",
    values: "{text}",
  },
  {
    id: "project.appHelpFile",
    friendly: "项目: 应用程序帮助文件",
    description:
      "这是可在运行时通过App.HelpFile属性访问的，并且在表单运行时帮助系统(F1 / WhatsThis)中使用",
    values: "{text}",
  },
  {
    id: "project.startupObject",
    friendly: "项目: 启动对象",
    description:
      "这是在启动时显示的表单，或'Sub Main'。 如果未指定，则'Sub Main'是EXE的默认，'(none)'是DLL的默认。",
    values: "",
    filterValues(e, t) {
      if (t === "(none)") {
        if (e["project.buildType"] === "Standard EXE") {
          return false;
        }
      } else if (e["project.buildType"] === "Package TWINPACK") {
        return false;
      }
      return true;
    },
    validate(e, t) {
      if (e === "(none)") {
        if (t["project.buildType"] === "Standard EXE") {
          return "(none) not allowed in Standard EXEs";
        }
      }
      return true;
    },
  },
  {
    id: "project.references",
    friendly: "库引用",
    description:
      "选择将用于编译此项目的引用",
    values: "{references}",
  },
  {
    id: "project.warnings",
    friendly: "编译警告",
    description:
      "定义编译器如何处理在此项目中内部的警告。 这些设置可以被覆盖类/模块/过程属性：<pre>[ EnforceWarnings(TBxxxx) ]</pre><pre>[ EnforceErrors(TBxxxx) ]</pre><pre>[ IgnoreWarnings(TBxxxx) ]</pre>",
    values: "{warnings}",
  },
  {
    id: "project.id",
    friendly: "项目: GUID",
    description: "一个唯一的GUID，表示此项目。",
    values: "{text}",
    validate(e) {
      var t = /^[{]?[0-9a-fA-F]{8}-([0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}[}]?$/;
      if (!t.test(e)) return "invalid GUID";
      return true;
    },
    refreshUUID: true,
  },
  {
    id: "project.useProjectIdForTypeLibraryId",
    friendly: "项目: 使用项目ID作为类型库ID",
    description:
      "如果是，编译器将使用项目ID作为类型库ID。 如果否，在生成过程中将生成一个唯一的类型库ID。",
    values: "{bool}",
  },
  {
    id: "project.buildPath",
    friendly: "项目: 编译输出路径",
    description:
      "输入编译器将创建的文件的完整路径。 可用变量：${SourcePath}, ${ProjectName}, ${ProjectID}, ${FileExtension}, ${Architecture}, ${VersionMajor}, ${VersionMinor}, ${VersionBuild}, ${VersionRevision}",
    values: "{text}",
  },
  {
    id: "project.buildType",
    friendly: "项目: 编译类型",
    description: "编译器生成的文件类型。",
    values:
      "Standard EXE,ActiveX DLL,ActiveX Control,Standard DLL,Package TWINPACK",
    rebuildUI: true,
  },
  {
    id: "project.licence",
    friendly: "项目: 许可类型",
    description:
      "对于推送到包数据库中的包，这允许用户清楚地看到您的包的许可证",
    values: "{text}",
  },
  {
    id: "project.packageVisibility",
    friendly: "项目: 包可见性",
    description:
      "对于推送到包数据库中的包，这确定包是否对所有人可用(公共)或仅发布者可用(私有)",
    values: "PRIVATE,PUBLIC",
  },
  {
    id: "project.versionMajor",
    friendly: "项目: 版本信息(主版本)",
    description: "与构建关联的主版本号。",
    values: "{int}",
    validate(e) {
      if (e < 0 || e > 65535) {
        return "value must be in the range 0-65535";
      }
      return true;
    },
  },
  {
    id: "project.versionMinor",
    friendly: "项目: 版本信息(次版本)",
    description: "与构建关联的次版本号。",
    values: "{int}",
    validate(e) {
      if (e < 0 || e > 65535) {
        return "value must be in the range 0-65535";
      }
      return true;
    },
  },
  {
    id: "project.versionBuild",
    friendly: "项目: 版本信息(编译版本)",
    description: "与构建关联的构建版本号。",
    values: "{int}",
    validate(e) {
      if (e < 0 || e > 65535) {
        return "value must be in the range 0-65535";
      }
      return true;
    },
  },
  {
    id: "project.versionRevision",
    friendly: "项目: 版本信息(修订版本)",
    description: "与构建关联的修订版本号。",
    values: "{int}",
    validate(e) {
      if (e < 0 || e > 65535) {
        return "value must be in the range 0-65535";
      }
      return true;
    },
  },
  {
    id: "project.versionProductName",
    friendly: "项目: 版本信息(产品名称)",
    description:
      "将在生成此文件版本信息资源时包含的ProductName文本。",
    values: "{text}",
  },
  {
    id: "project.versionCompanyName",
    friendly: "项目: 版本信息(公司名称)",
    description:
      "将在生成此文件版本信息资源时包含的CompanyName文本。",
    values: "{text}",
  },
  {
    id: "project.versionFileDescription",
    friendly: "项目: 版本信息(文件描述)",
    description:
      "将在生成此文件版本信息资源时包含的文件Description文本。",
    values: "{text}",
  },
  {
    id: "project.versionLegalCopyright",
    friendly: "项目: 版本信息(法律版权)",
    description:
      "将在生成此文件版本信息资源时包含的 LegalCopyright文本。",
    values: "{text}",
  },
  {
    id: "project.versionLegalTrademarks",
    friendly: "项目: 版本信息(商标)",
    description:
      "将在生成此文件版本信息资源时包含的 LegalTrademarks文本。",
    values: "{text}",
  },
  {
    id: "project.versionComments",
    friendly: "项目: 版本信息(注释)",
    description:
      "将在生成此文件版本信息资源时包含的注释。",
    values: "{text}",
  },
  {
    id: "project.versionAutoIncrement",
    friendly: "项目: 版本信息(自动递增)",
    description:
      "如果希望在成功生成后自动增加版本号，请在此处选择要增加的构建号部分。 VB6总是使用修订字段进行自动增量字段。",
    values: "None,Revision,Build,Minor,Major",
  },
  {
    id: "project.dllRegisterLocalMachine",
    friendly: "项目: 注册DLL到HKEY_LOCAL_MACHINE",
    description:
      '如果编译类型是[ActiveX DLL]或[ActiveX Control]，则此标志影响生成的DllRegisterServer/DllUnregisterServer实现，导致DLL被注册到HKEY_LOCAL_MACHINE注册表hive而不是HKEY_CURRENT_USER。 VB6 DLLs注册到HKEY_LOCAL_MACHINE注册表hive，但这需要提升权限。如果此选项设置为YES，通常需要打开IDE并选择“以管理员身份运行”选项。 ',
    values: "{bool}",
  },
  {
    id: "project.dllRegisterAfterBuild",
    friendly: "项目: 编译后注册DLL",
    description:
      "如果编译类型是[ActiveX DLL]或[ActiveX Control]，则此标志设置为YES会导致生成的DLL在生成后立即自动注册IDE。如果要手动控制生成的DLL的注册，请将其设置为NO。",
    values: "{bool}",
  },
  {
    id: "project.comInitialization",
    friendly: "项目: COM初始化",
    description:
      "选择如何在生成的EXE中初始化COM/OLE。默认值为OleInitialize，与VB6匹配。此选项对DLL构建没有影响。此选项允许您覆盖线程模型[ STA/MTA ]",
    values:
      "OleInitialize STA (Single Threaded Apartment),MTA (CoInitializeEx - Multi Threaded Apartment),STA (CoInitialize - Single Threaded Apartment)",
  },
  {
    id: "project.isConsoleApplication",
    friendly: "项目: 控制台应用程序",
    description:
      "如果YES，生成的可执行文件将被标记为CONSOLE应用程序，而不是GUI应用程序。",
    values: "{bool}",
  },
  {
    id: "project.isNativeSubsystem",
    friendly: "项目: 本地子系统(高级)",
    description:
      "如果YES，生成的编译将被标记为NATIVE（IMAGE_SUBSYSTEM_NATIVE），适用于内核设备驱动程序",
    values: "{bool}",
  },
  {
    id: "project.overrideEntryPoint",
    friendly: "项目: 重写入口点(高级)",
    description:
      "如果提供过程名称，则将使用生成的可执行文件的入口点。通过覆盖此选项，您负责所有子系统的初始化，例如COM/OLE。此选项通常只用于本机内核模式构建。",
    values: "{text}",
  },
  {
    id: "project.dllRuntimeBinding",
    friendly: "项目: DLL声明的运行时绑定(高级)",
    description:
      "如果YES，编译器将在运行时解析项目内部声明。如果NO，编译器将在生成的可执行文件中添加到导入地址表（IAT）中。注意：此设置不影响在类型库中定义的DLL声明，因为它们总是添加到IAT中。",
    values: "{bool}",
  },
  {
    id: "project.conditionalCompilationArguments",
    friendly: "项目: 条件编译参数",
    description:
      "在编译器进行条件编译评估时，请输入以冒号分隔的名称=值对列表。范围为-32768到32767的值是允许的。例如：foo=42:bar=-42",
    values: "{text}",
  },
  {
    id: "project.optionExplicit",
    friendly: "项目: 显式指定(高级)",
    description:
      "如果在源文件中未指定Option Explicit On/Off，则此选项将生效",
    values: "{bool}",
  },
  {
    id: "project.autoPrettify",
    friendly: "项目: 自动美化源代码",
    description:
      "如果设置为YES，当您键入时，将自动纠正单词的大小写，并将间距纠正为VBE标准。",
    values: "{bool}",
  },
  {
    id: "project.codeLensRunProcedure",
    friendly: "项目: 显示运行过程",
    description:
      '如果设置为YES，“▶   运行 {过程名称}”将在标准模块中显示在无参数过程的CodeLens上',
    values: "{bool}",
  },
  {
    id: "runtime.useUnicodeStandardLibrary",
    friendly: "运行时: 使用Unicode标准库",
    description:
      "如果设置为YES，编译器将尽可能使用Unicode版本的Windows API调用（例如，MsgBox将调用MessageBoxW而不是MessageBoxA）",
    values: "{bool}",
  },
  {
    id: "compiler.includeStackSymbols",
    friendly:
      "编译: 在内建可执行文件中包含过程名称符号",
    description:
      '如果设置为YES，编译器将在生成的EXE和DLL中包括过程名称符号。这些符号用于枚举实时调用堆栈信息。当禁用时，ErrorStackFrame接口将返回“{unknown}”对于在生成的可执行文件中定义的符号。当启用时，此选项会微小增加生成的可执行文件的大小，但不会影响运行时性能。',
    values: "{bool}",
  },
  {
    id: "compiler.symbolTableMaxSizeHash",
    friendly: "编译: 符号表最大大小哈希",
    description:
      "增加此值使用更多内存，但对于较大的项目会提高编译性能。注意：编译器将警告您达到此限制时需要更改此值",
    values: "{int}",
    validate(e) {
      var t = (e & (e - 1)) == 0;
      if (!t) return "must be power of 2";
      return true;
    },
  },
  {
    id: "compiler.symbolTableMaxSizeRaw",
    friendly: "编译: 符号表最大大小原始",
    description:
      "增加此值使用更多内存，但允许较大的项目的编译。注意：编译器将警告您达到此限制时需要更改此值",
    values: "{int}",
  },
  {
    id: "compiler.symbolTableMaxSizeLookup",
    friendly: "编译: 符号表最大大小查找",
    description:
      "增加此值使用更多内存，但允许较大的项目的编译。注意：编译器将警告您达到此限制时需要更改此值",
    values: "{int}",
  },
  {
    id: "compiler.symbolTableDataTypeLookup",
    friendly: "编译: 符号表数据类型查找",
    description:
      "增加此值使用更多内存，但允许较大的项目的编译。注意：编译器将警告您达到此限制时需要更改此值",
    values: "{int}",
  },
  {
    id: "compiler.sanitizeBooleans",
    friendly: "编译: 布尔值消毒",
    description:
      "如果设置为YES，编译器确保从外部源输出的布尔值包含绝对True[-1]或False[0]值。这可以确保将不适当的值（例如[1]）打包到布尔数据类型中。小性能影响。",
    values: "{bool}",
  },
  {
    id: "optimizer.constantFunctionFolding",
    friendly: "优化: 常量函数折叠",
    description:
      "(试验性)如果设置为YES，编译器将在编译时将一些函数调用转换为常量字面量，当结果已知且在编译时完全确定时。此设置仅影响VBA标准库中的函数调用，以及您已显式标记为[ ConstantFoldable ]的任何标准模块函数。",
    values: "{bool}",
  },
  {
    id: "project.largeAddressAware",
    friendly: "项目: 大地址感知",
    description:
      "如果设置为YES，此项目的32位EXE构建将具有“大地址感知”标志，允许它们访问4GB内存。如果NO，32位EXE构建受限于2GB内存空间。使用时请谨慎，因为您的代码和任何第三方DLL必须兼容。",
    values: "{bool}",
  },
  {
    id: "project.terminalServerAware",
    friendly: "项目: 终端服务器感知",
    description:
      "如果设置为YES，生成的可执行文件将被标记为TS-Aware。此标志影响一些Windows API调用，例如在Terminal Server上运行时Get-Windows-Directory，当运行时运行时Get-Windows-Directory",
    values: "{bool}",
  },
  {
    id: "project.depAware",
    friendly: "项目: 数据执行防护感知",
    description:
      "如果设置为YES，生成的可执行文件将被标记为DEP-Aware。在兼容的硬件上，这将保护您的可执行文件免受运行时代码注入攻击的影响",
    values: "{bool}",
  },
  {
    id: "project.exportPath",
    friendly: "项目: 导出路径",
    description:
      "输入将用于“导出项目”命令的路径。当设置时，将使用此路径而不是每次调用命令时都提示用户。<br/><br/><b style='background: red; color: white; border-radius: 5px; padding: 5px;'>警告：请谨慎！在导出之前，导出文件夹将被清除，以确保导出是干净的。<br/><br/>可用的变量：${SourcePath}, ${ProjectName}, ${ProjectFileName}, ${ProjectID}, ${FileExtension}, ${VersionMajor}, ${VersionMinor}, ${VersionBuild}, ${VersionRevision}",
    values: "{text}",
    validate(e) {
      if (!e) return true;
      var t =
        e.toLowerCase() !== "${sourcepath}" &&
        e.toLowerCase() !== "${sourcepath}\\";
      if (!t)
        return "${SourcePath} on it's own is not allowed.  This would DELETE the project file, as the `Export Project` command empties the output folder before exporting.  Append a subfolder, such as `${SourcePath}\\${ProjectName}`";
      return true;
    },
    firstEnabled() {
      return "${SourcePath}\\${ProjectName}";
    },
  },
  {
    id: "project.exportAfterSave",
    friendly: "项目: 保存后导出",
    description:
      "当此选项设置为YES时，“导出项目”将自动运行，使用提供的导出路径设置，立即在保存twinproj文件到磁盘后。</b>",
    values: "{bool}",
  },
  {
    id: "project.exportVerbose",
    friendly: "项目: 导出详细",
    description:
      "当此选项设置为YES时，“导出项目”将报告每个文件操作（即使成功）。</b>",
    values: "{bool}",
  },
  {
    id: "project.forceDpiAwarenessAtStartup",
    friendly: "项目: 强制DPI感知启动",
    description:
      "将此选项设置为无来关闭DPI感知，或者通过手动创建清单来控制应用程序的DPI感知。在这里设置其他值将导致使用SetProcessDpiAwareness API的可用性。",
    values: "无,系统DPI感知,按每个监视器DPI感知",
  },
  {
    id: "debugger.runtimeCommandLineArguments",
    friendly: "调试器: 运行时命令行参数",
    description:
      "在这里输入的文本将在运行时调试会话中通过VBA.Interaction.Command$函数可用",
    values: "{text}",
  },
  {
    id: "debugger.immediateMemoryInvalidation",
    friendly: "调试器: 即时内存无效",
    description:
      "如果设置为YES，当释放诸如字符串、Variant和数组之类的实时值时，它们的原始内容首先被覆盖为垃圾数据。  操作系统通常不会在绝对必要时擦除内存的内容（即当内存区域被重新使用时）。  这往往导致错误的假设，即指针的生存期。在大多数情况下，您可能可以通过使用过时的指针来绕过这些错误，但这会导致非常微妙的错误，只有偶尔才会出现。使用此功能来帮助检测代码中的这些错误。在调试时会有小的性能影响。在大多数情况下，您可能可以通过使用过时的指针来绕过这些错误，但这会导致非常微妙的错误，只有偶尔才会出现。使用此功能来帮助检测代码中的这些错误。在调试时会有小的性能影响。",
    values: "{bool}",
  },
  {
    id: "project.buildStackReserveSize",
    friendly: "项目: 构建堆栈预留大小",
    description:
      "更改此值会修改生成的可执行文件的PE标头。默认值为1MB。如果您在运行时遇到堆栈溢出错误，请尝试增加此值。",
    values: "{int}",
    validate(e) {
      var t = Math.round(e / 4096) * 4096 === e;
      if (!t) return "必须是4096的倍数";
      return true;
    },
  },
];
var warningsTable = [
  {
    id: "TB0001",
    description: "不建议使用旧的DefType语句",
  },
  {
    id: "TB0002",
    description:
      "由于Option Explicit为OFF，编译器自动声明了此变量",
  },
  {
    id: "TB0003",
    description:
      "未显式声明数据类型，将默认为Variant",
  },
  {
    id: "TB0004",
    description:
      "[Exit Property] 仅用于向后兼容。请使用 [Exit Property] 代替。",
  },
  { id: "TB0005", description: "#警告指令已被发现" },
  { id: "TB0006", description: "二进制模式下，记录长度被忽略" },
  { id: "TB0007", description: "数据类型提示不匹配" },
  { id: "TB0008", description: "可疑的调用" },
  { id: "TB0009", description: "成员未实现" },
  { id: "TB0010", description: "检测到重复的DLL声明" },
  {
    id: "TB0011",
    description:
      "不建议使用旧的日期/时间属性-Let赋值",
  },
  {
    id: "TB0012",
    description: "可能的十六进制字面量使用错误",
  },
  {
    id: "TB0013",
    description:
      "强烈建议为此类指定 [ InterfaceId() ] 属性",
  },
  {
    id: "TB0014",
    description: "User Defined Types 上的ByVal属性被忽略",
  },
  {
    id: "TB0015",
    description:
      "已将旧的DLL {LEGACY.DLL} 重定向到 {MODERN.DLL}",
  },
  { id: "TB0016", description: "ReDim 隐式创建变量" },
];
("use strict");
const properties = {
  "configuration.name": "Defaults",
  "configuration.inherits": "",
  "compiler.target": "",
  "compiler.autoRestart": true,
  "compiler.includeStackSymbols": false,
  "project.id": "",
  "project.useProjectIdForTypeLibraryId": false,
  "project.name": "NewProject",
  "project.versionMajor": 1,
  "project.versionMinor": 0,
  "project.versionRevision": 0,
  "project.versionBuild": 0,
  "project.versionComments": "",
  "project.versionCompanyName": "",
  "project.versionLegalCopyright": "",
  "project.versionLegalTrademarks": "",
  "project.versionProductName": "",
  "project.versionFileDescription": "",
  "project.versionAutoIncrement": "None",
  "project.description": "",
  "project.appTitle": "",
  "project.appHelpFile": "",
  "project.references": [],
  "project.optionExplicit": true,
  "project.autoPrettify": true,
  "project.conditionalCompilationArguments": "",
  "project.buildPath":
    "${SourcePath}\\Build\\${ProjectName}_${Architecture}.${FileExtension}",
  "project.buildType": "Standard EXE",
  "project.dllRegisterLocalMachine": false,
  "project.dllRegisterAfterBuild": true,
  "project.comInitialization": "OleInitialize STA (Single Threaded Apartment)",
  "project.isConsoleApplication": false,
  "project.isNativeSubsystem": false,
  "project.dllRuntimeBinding": true,
  "project.overrideEntryPoint": "",
  "project.codeLensRunProcedure": true,
  "project.packageVisibility": "PRIVATE",
  "project.exportPath": "",
  "project.exportVerbose": false,
  "project.forceDpiAwarenessAtStartup": "按每个监视器DPI感知",
  "debugger.optionExplicit": true,
  "debugger.stackedBreakpoints": true,
  "debugger.fullRefreshOnSetVariable": true,
  "debugger.preferEarlyBoundInterfaces": true,
  "debugger.sortLocalsAlphabetically": true,
  "debugger.sortUDTsAlphabetically": false,
  "debugger.sortFieldsAlphabetically": true,
  "debugger.showUDTPadding": false,
  "debugger.showHexValues": false,
  "debugger.showHiddenMembers": false,
  "debugger.showObjectPointerValues": true,
  "debugger.consoleLogTimeTaken": true,
  "debugger.runtimeCommandLineArguments": "",
  "runtime.useUnicodeStandardLibrary": false,
  "compiler.symbolTableMaxSizeHash": 262144,
  "compiler.symbolTableMaxSizeRaw": 2097152,
  "compiler.symbolTableMaxSizeLookup": 2097152,
  "compiler.symbolTableDataTypeLookup": 262144,
  "compiler.sanitizeBooleans": false,
  "optimizer.constantFunctionFolding": false,
  "project.largeAddressAware": false,
  "project.depAware": false,
  "project.terminalServerAware": false,
  "intellisense.showHiddenMembers": false,
  "intellisense.showEventInterfaces": false,
  "intellisense.showDefaultInheritedInterfaces": false,
  "intellisense.hideLeadingUnderscoreElements": true,
  "ide.compilerPortNumber": 0,
  "ide.lspPortNumber": 0,
  "ide.dapPortNumber": 0,
  "ide.fsPortNumber": 0,
  "project.buildStackReserveSize": 1048576,
};
("use strict");
function librarySymbolRequest(e, t, o) {
  e.vscode.postMessage({ type: "librarySymbolRequest", args: [t, o] });
}
function _librarySymbolResponse(e, t, o) {
  if (e.symbolRequests[t]) {
    var n = e.symbolRequests[t];
    if (o === "<UNKNOWN>") {
      if (!n.classList.contains("clickable")) {
        o = "<MISSING>";
      }
    }
    n.innerText = o;
    n.classList.remove("clickable");
    delete e.symbolRequests[t];
    if (n.element) {
      n.element.symbolId = o;
    }
  }
}
function configDataUpdated(e) {
  doValidation(e);
  e.vscode.postMessage({ type: "onChanged", args: [e.configData] });
}
function updateCssVars(e) {
  document.documentElement.style.setProperty(
    "--inheritsFromText",
    `"继承自 [${e.configData["configuration.inherits"]}]"`
  );
}
function changeOption(e, t, o) {
  e.configData[t] = o;
  e.schema.forEach((o) => {
    if (o.id === t) {
      if (o.rebuildUI) {
        configEditor_initUI(e);
        return false;
      }
    }
  });
  configEditor_refreshUI(e);
  configDataUpdated(e);
}
function removeOption(e, t) {
  delete e.configData[t];
  configDataUpdated(e);
}
function reference_remove(e, t) {
  e.configData["project.references"] = e.configData[
    "project.references"
  ].filter(
    (e) =>
      !(
        e.id === t.id &&
        e.versionMajor === t.versionMajor &&
        e.versionMinor === t.versionMinor &&
        e.versionRevision === t.versionRevision &&
        e.versionBuild === t.versionBuild &&
        e.lcid === t.lcid
      )
  );
}
function reference_toggle(e, t, o) {
  e.referencesSaveWarningDiv.classList.add("animateHiddenOff");
  if (t.id == "{54F90FBF-5CDC-41D6-AEC2-983DEF203B07}") {
    e.configData["project.disablePackageVBA"] = e.configData[
      "project.disablePackageVBA"
    ]
      ? false
      : true;
    e.allReferencesListNew.innerHTML = "";
    configDataUpdated(e);
    configEditor_refreshUI(e);
    return;
  }
  if (t.id == "{8BEB50D8-B4BB-44C7-9784-35AF50ABC872}") {
    e.configData["project.disablePackageVBRUN"] = e.configData[
      "project.disablePackageVBRUN"
    ]
      ? false
      : true;
    e.allReferencesListNew.innerHTML = "";
    configDataUpdated(e);
    configEditor_refreshUI(e);
    return;
  }
  if (t.isOnlinePackage) {
    e.vscode.postMessage({
      type: "importOnlinePackage",
      args: [
        t.id,
        t.versionMajor,
        t.versionMinor,
        t.versionRevision,
        t.versionBuild,
      ],
    });
    return;
  }
  if (o === "true" || o === true) {
    reference_remove(e, t);
    if (
      t.path32 &&
      t.path32.indexOf("/Packages/") == 0 &&
      t.isCompilerPackage === undefined
    ) {
      e.vscode.postMessage({
        type: "askDeleteImportedPackage",
        args: [t.path32],
      });
    }
  } else {
    var n = t.htmlOpt;
    t.htmlOpt = undefined;
    e.configData["project.references"].push(JSON.parse(JSON.stringify(t)));
    t.htmlOpt = n;
  }
  e.allReferencesListNew.innerHTML = "";
  configDataUpdated(e);
  configEditor_refreshUI(e);
}
function reference_moveUp(e, t, o) {
  var n = parseInt(o);
  if (n > 0) {
    reference_remove(e, t);
    e.configData["project.references"].splice(n - 1, 0, t);
    configDataUpdated(e);
    configEditor_refreshUI(e);
  }
}
function reference_moveDown(e, t, o) {
  var n = parseInt(o);
  if (n < e.configData["project.references"].length) {
    reference_remove(e, t);
    e.configData["project.references"].splice(n + 1, 0, t);
    configDataUpdated(e);
    configEditor_refreshUI(e);
  }
}
function doValidation(e) {
  e.schema.forEach((t) => {
    if (t.errorsDiv) {
      t.errorsDiv.innerHTML = "";
      if (t.validate !== undefined) {
        var o = t.validate(e.configData[t.id], e.configData);
        if (o !== true) {
          t.errorsDiv.innerHTML = `校验失败： ${o}`;
        }
      }
    }
  });
}
function HTMLOptionSelectHandler(e, t) {
  var o = t.target.options[t.target.options.selectedIndex];
  var n = JSON.parse(o.getAttribute("customInfo_Object"));
}
function HTMLOptionSelectHandlerENABLED(e, t) {
  var o = t.target.options[t.target.options.selectedIndex];
  var n = JSON.parse(o.getAttribute("customInfo_Object"));
}
function HTMLOptionDoubleClickHandler(e, t) {
  var o = JSON.parse(t.target.getAttribute("customInfo_Object"));
  reference_toggle(e, o, t.target.getAttribute("customInfo_IsEnabled"));
}
function HTMLSelectKeypressHandler(e, t) {
  if (t.key.length > 1) return;
  var o = performance.now() - t.target.lastKeyPressTime;
  if (isNaN(o)) o = 99999;
  t.target.lastKeyPressTime = performance.now();
  var n;
  if (o < 1250) {
    n = t.target.lastSearchString + t.key.toLowerCase();
  } else {
    if (t.key === " ") {
      var i = t.target.childNodes[t.target.selectedIndex];
      var r = JSON.parse(i.getAttribute("customInfo_Object"));
      reference_toggle(e, r, i.getAttribute("customInfo_IsEnabled"));
      return;
    }
    n = t.key.toLowerCase();
  }
  t.target.lastSearchString = n;
  var s = 0;
  t.target.childNodes.forEach((e) => {
    if (e.value.toLowerCase().substring(0, n.length) == n) {
      t.target.selectedIndex = s;
      return false;
    }
    s++;
  });
}
function referenceSearchClicked(e) {
  configEditor_debugMsg(e, "referenceSearchClicked");
}
function configEditor_initUIHeader(e) {
  e.rootElement.innerHTML = e.initialHTML;
  (e.optionsHeader = e.rootElement.querySelector(".optionsHeader")),
    (e.optionsHeader.innerHTML = "");
  var t = document.createElement("div");
  t.className = "filterBanner";
  e.optionsHeader.appendChild(t);
  var o = document.createElement("input");
  o.className = "filterBar";
  o.type = "text";
  o.value = e.CurrentFilter ? e.CurrentFilter : "(输入文本进行过滤...)";
  o.onfocus = () => {
    if (!e.CurrentFilter) {
      o.value = "";
      return;
    } else {
      o.selectionStart = 0;
      o.selectionEnd = 999999999999;
    }
  };
  o.oninput = () => {
    e.CurrentFilter = o.value;
    configEditor_initUI(e);
    configEditor_refreshUI(e);
    o.focus();
  };
  o.onblur = () => {
    e.CurrentFilter = o.value;
    if (!e.CurrentFilter) {
      o.value = "(输入文本进行过滤...)";
    }
    configEditor_initUI(e);
    configEditor_refreshUI(e);
  };
  o.onkeydown = (e) => {
    if (e.key == "Escape") {
      o.value = "";
      o.blur();
    }
  };
  t.appendChild(o);
}
function containsAll(e, t, o) {
  t = t.toLowerCase();
  var n = false;
  o.forEach((e) => {
    if (t.indexOf(e) == -1) {
      n = true;
    }
  });
  return !n;
}
function configEditor_initUI(e) {
  (e.optionsContainer = e.rootElement.querySelector(".options")),
    (e.headerContainer = e.rootElement.querySelector(".header")),
    (e.optionsContainer.innerHTML = "");
  var t = document.createElement("div");
  t.className = "filterBannerUnderneathSpace";
  e.optionsContainer.appendChild(t);
  var o = e.CurrentFilter ? e.CurrentFilter.toLowerCase().split(" ") : [];
  e.schema.forEach((t) => {
    if (e.CurrentFilter) {
      t.rootDiv = undefined;
      t.errorsDiv = undefined;
      if (t.id == e.CurrentFilter) {
      } else if (
        containsAll(e, t.id, o) ||
        containsAll(e, t.friendly, o) ||
        containsAll(e, t.description, o)
      ) {
      } else {
        return;
      }
    }
    var n = document.createElement("div");
    n.className = t.id + " optionDisabled";
    t.rootDiv = n;
    var i = document.createElement("input");
    i.type = "checkbox";
    i.className = t.id + "_ENABLER optionEnabler";
    n.appendChild(i);
    t.enablerDiv = i;
    var r = document.createElement("div");
    r.className = t.id + "_HEADER optionHeader";
    r.innerHTML = t.friendly;
    n.appendChild(r);
    t.headerDiv = i;
    var s = document.createElement("div");
    s.className = t.id + "_DESCRIPTION optionDescription";
    s.innerHTML = t.description;
    n.appendChild(s);
    t.descriptionDiv = u;
    var a = document.createElement("div");
    a.className = t.id + "_DESCRIPTION optionSaveWarning animateHidden";
    a.innerHTML =
      "请注意：当前修改需要在保存设置文档并重新启动编译器后生效。";
    n.appendChild(a);
    t.descriptionDiv = u;
    var l = document.createElement("div");
    l.className = t.id + "_CONTENT optionContent";
    n.appendChild(l);
    t.contentDiv = i;
    if (t.values === "{text}") {
      var d = document.createElement("input");
      d.type = "text";
      d.className = t.id + "_TEXT optionContentInner optionContentInnerText";
      l.appendChild(d);
      t.contentInnerDiv = d;
      d.oninput = (o) => {
        changeOption(e, t.id, d.value);
        a.classList.add("animateHiddenOff");
      };
      t.setValue = (e) => {
        d.value = e;
      };
      t.inputElement = d;
      if (t.refreshUUID !== undefined) {
        var c = document.createElement("div");
        c.type = "text";
        c.className = t.id + "_REFRESH refreshButton";
        c.innerHTML = "↻";
        c.title = "Generate a new GUID";
        l.appendChild(c);
        c.onclick = () => {
          d.value = generateUUID();
          changeOption(e, t.id, d.value);
          a.classList.add("animateHiddenOff");
        };
      }
    } else if (t.values === "{int}") {
      var d = document.createElement("input");
      d.type = "number";
      d.className = t.id + "_NUMBER optionContentInner optionContentInnerText";
      l.appendChild(d);
      t.contentInnerDiv = d;
      d.oninput = (o) => {
        changeOption(e, t.id, parseInt(d.value));
        a.classList.add("animateHiddenOff");
      };
      t.setValue = (e) => {
        d.value = e.toString();
      };
      t.inputElement = d;
    } else if (t.values === "{bool}") {
      var u = document.createElement("select");
      u.className = t.id + "_SELECT optionContentInner";
      u.onkeydown = (t) => HTMLSelectKeypressHandler(e, t);
      var p = document.createElement("option");
      p.innerHTML = "No";
      u.options.add(p);
      p = document.createElement("option");
      p.innerHTML = "Yes";
      u.options.add(p);
      l.appendChild(u);
      t.contentInnerDiv = u;
      u.oninput = (o) => {
        changeOption(e, t.id, u.selectedIndex === 1 ? true : false);
        a.classList.add("animateHiddenOff");
      };
      t.setValue = (e) => {
        u.selectedIndex = e ? 1 : 0;
      };
      if (t.validate === undefined) {
        t.validate = (e) => {
          if (e !== undefined && e !== true && e !== false) {
            return `invalid value`;
          }
          return true;
        };
      }
      t.inputElement = u;
    } else if (t.values === "{warnings}") {
      var f = document.createElement("div");
      f.className = "warningOptions";
      n.appendChild(f);
      e.warningsTable.forEach((o) => {
        var n = document.createElement("div");
        n.className = "warningDiv";
        f.appendChild(n);
        var i = document.createElement("select");
        i.className = "warningState";
        i.onkeydown = (t) => HTMLSelectKeypressHandler(e, t);
        n.appendChild(i);
        var r = document.createElement("option");
        r.innerHTML = "WARNING";
        r.value = 0;
        i.options.add(r);
        r = document.createElement("option");
        r.innerHTML = "IGNORE";
        r.value = 1;
        r.className = "warning_" + o.id + "_ignore";
        i.options.add(r);
        r = document.createElement("option");
        r.innerHTML = "ERROR";
        r.value = 2;
        r.className = "warning_" + o.id + "_error";
        i.options.add(r);
        i.onchange = () => {
          var n = e.configData[t.id];
          n.ignored = n.ignored.filter((e) => e !== o.id);
          n.errors = n.errors.filter((e) => e !== o.id);
          if (i.value == 1) {
            n.ignored.push(o.id);
          } else if (i.value == 2) {
            n.errors.push(o.id);
          }
          changeOption(e, t.id, n);
          a.classList.add("animateHiddenOff");
        };
        var s = document.createElement("div");
        s.className = "warningDescription";
        s.innerHTML = "<b>" + o.id + "</b> &nbsp;&nbsp;&nbsp;" + o.description;
        n.appendChild(s);
      });
      t.inputElement = f;
      t.setValue = (e) => {
        e.ignored.forEach((e) => {
          var t = document.getElementsByClassName(
            "warning_" + e + "_ignore"
          )[0];
          if (t) t.selected = true;
        });
        e.errors.forEach((e) => {
          var t = document.getElementsByClassName("warning_" + e + "_error")[0];
          if (t) t.selected = true;
        });
      };
    } else if (t.values === "{references}") {
      e.referencesSaveWarningDiv = a;
      {
        let t = document.createElement("div");
        t.className = "referencesListChoice";
        n.appendChild(t);
        let o = document.createElement("div");
        o.innerText = "已启用的库";
        o.title =
          "显示此项目中启用的库（引用/包）列表";
        o.className =
          "referencesListChoiceOption referencesListChoiceOptionSelected";
        o.onclick = () => {
          o.classList.add("referencesListChoiceOptionSelected");
          i.classList.remove("referencesListChoiceOptionSelected");
          r.classList.remove("referencesListChoiceOptionSelected");
          e.referencesListNew.parentNode.classList.remove(
            "referenceListHidden"
          );
          e.allReferencesListNew.parentNode.classList.add(
            "referenceListHidden"
          );
          e.allPackagesListNew.parentNode.classList.add("referenceListHidden");
          e.filter = e.filterReferences;
          e.notLoggedInWarning.style = "display: none";
        };
        t.appendChild(o);
        let i = document.createElement("div");
        i.innerText = "可用的COM引用";
        i.title = "显示此计算机上可用的引用列表";
        i.className = "referencesListChoiceOption";
        i.onclick = () => {
          o.classList.remove("referencesListChoiceOptionSelected");
          i.classList.add("referencesListChoiceOptionSelected");
          r.classList.remove("referencesListChoiceOptionSelected");
          e.referencesListNew.parentNode.classList.add("referenceListHidden");
          e.allReferencesListNew.parentNode.classList.remove(
            "referenceListHidden"
          );
          e.allPackagesListNew.parentNode.classList.add("referenceListHidden");
          e.filter = e.filterReferences;
          e.allReferencesListNew.innerHTML = "";
          e.referencesListMode = 1;
          configEditor_refreshUI(e);
          e.filter.focus();
        };
        t.appendChild(i);
        let r = document.createElement("div");
        r.innerText = "可用的包";
        r.title = "显示可用的TWINPACK包列表";
        r.className = "referencesListChoiceOption";
        r.onclick = () => {
          o.classList.remove("referencesListChoiceOptionSelected");
          i.classList.remove("referencesListChoiceOptionSelected");
          r.classList.add("referencesListChoiceOptionSelected");
          e.referencesListNew.parentNode.classList.add("referenceListHidden");
          e.allReferencesListNew.parentNode.classList.add(
            "referenceListHidden"
          );
          e.allPackagesListNew.parentNode.classList.remove(
            "referenceListHidden"
          );
          e.filter = e.filterPackages;
          e.allPackagesListNew.innerHTML = "";
          e.referencesListMode = 2;
          e.vscode.postMessage({ type: "getOnlinePackages" });
          configEditor_refreshUI(e);
          e.filter.focus();
        };
        t.appendChild(r);
      }
      {
        let t = document.createElement("div");
        t.className = "referencesListNewOuter";
        n.appendChild(t);
        let o = document.createElement("div");
        o.className = "referencesListRowHeader";
        t.appendChild(o);
        let i = document.createElement("div");
        i.className = "referencesListNew";
        t.appendChild(i);
        e.referencesListNew = i;
        let r = document.createElement("div");
        r.className = "referencesListColEnabled";
        r.innerText = "";
        o.appendChild(r);
        let s = document.createElement("div");
        s.className = "referencesListColName";
        s.innerText = "Name";
        s.title = "Name: The name of the COM reference or package";
        o.appendChild(s);
        let a = document.createElement("span");
        a.className = "subText";
        a.innerText = "in order of priority";
        s.appendChild(a);
        let l = document.createElement("div");
        l.className = "referencesListColMove";
        o.appendChild(l);
        let d = document.createElement("div");
        d.className = "referencesListColSymbol";
        d.innerText = "Library Symbol";
        d.title =
          "Library Symbol: the text symbol used to refer to the library within the project";
        o.appendChild(d);
        let c = document.createElement("div");
        c.className = "referencesListColVersion";
        c.innerText = "Version";
        c.title =
          "Version: the version number of the COM type library or package";
        o.appendChild(c);
        let u = document.createElement("div");
        u.className = "referencesListColPublisher";
        u.innerText = "Publisher";
        u.title = u.innerText;
        o.appendChild(u);
        let p = document.createElement("div");
        p.className = "referencesListColPaths";
        p.innerText = "Path";
        o.appendChild(p);
        let f = document.createElement("div");
        f.className = "referencesListColLibraryID";
        f.innerText = "LibraryID";
        o.appendChild(f);
        let g = document.createElement("div");
        g.className = "referencesListColLocale";
        g.innerText = "Locale";
        o.appendChild(g);
        let m = document.createElement("div");
        m.className = "referencesListColLicence";
        m.innerText = "Licence";
        m.title = m.innerText;
        o.appendChild(m);
        let h = document.createElement("div");
        h.className = "referencesListColPublishedDate";
        h.innerText = "Date";
        h.title = h.innerText;
        o.appendChild(h);
        let v = document.createElement("div");
        v.className = "referencesListColUseActiveXControls";
        v.innerText = "Use ActiveX Controls";
        v.title = v.innerText;
        o.appendChild(v);
      }
      {
        let t = document.createElement("div");
        t.className = "referencesListNewOuter referenceListHidden";
        n.appendChild(t);
        let o = document.createElement("div");
        o.className = "referencesListRowHeader";
        t.appendChild(o);
        let i = document.createElement("div");
        i.className = "referencesListNewAvailable";
        t.appendChild(i);
        e.allReferencesListNew = i;
        let r = document.createElement("div");
        r.className = "referencesListColEnabled";
        r.innerText = "";
        o.appendChild(r);
        let s = document.createElement("div");
        s.className = "referencesListColName2";
        o.appendChild(s);
        let a = document.createElement("span");
        a.className = "referenceSearchButton2";
        s.appendChild(a);
        let l = document.createElement("input");
        l.className = "referencesSearchBox";
        l.text = "Search...";
        l.type = "text";
        l.onkeydown = (t) => {
          if (t.key == "Escape") {
            l.value = e.cachedSearchBoxValueBefore;
            l.oninput();
          } else if (t.key == "Enter") {
          }
        };
        l.oninput = (t) => {
          i.innerHTML = "";
          e.HighlightAfterToggle = null;
          configEditor_refreshUI(e);
          if (l.value.length) {
          } else {
          }
        };
        l.onblur = () => {};
        e.filterReferences = l;
        e.filter = e.filterReferences;
        s.appendChild(l);
        a.onclick = () => {
          if (l.className === "referencesSearchBoxTransparent") {
            l.className = "referencesSearchBox";
            l.focus();
            l.select();
            e.cachedSearchBoxValueBefore = l.value;
          } else {
            l.className = "referencesSearchBoxTransparent";
          }
        };
        let d = document.createElement("div");
        d.className = "referencesListColSymbol";
        d.innerText = "Library Symbol";
        o.appendChild(d);
        let c = document.createElement("div");
        c.className = "referencesListColVersion";
        c.innerText = "Version";
        o.appendChild(c);
        let u = document.createElement("div");
        u.className = "referencesListColPublisher";
        u.innerText = "Publisher";
        u.title = u.innerText;
        o.appendChild(u);
        let p = document.createElement("div");
        p.className = "referencesListColPaths";
        p.innerText = "Path";
        o.appendChild(p);
        let f = document.createElement("div");
        f.className = "referencesListColLibraryID";
        f.innerText = "LibraryID";
        o.appendChild(f);
        let g = document.createElement("div");
        g.className = "referencesListColLocale";
        g.innerText = "Locale";
        o.appendChild(g);
        let m = document.createElement("div");
        m.className = "referencesListColLicence";
        m.innerText = "Licence";
        m.title = m.innerText;
        o.appendChild(m);
        let h = document.createElement("div");
        h.className = "referencesListColPublishedDate";
        h.innerText = "Date";
        h.title = h.innerText;
        o.appendChild(h);
      }
      {
        let t = document.createElement("div");
        t.className = "referencesListNewOuter referenceListHidden";
        n.appendChild(t);
        let o = document.createElement("div");
        o.className = "referencesListRowHeader";
        t.appendChild(o);
        let i = document.createElement("div");
        i.className = "referencesListNewAvailable";
        t.appendChild(i);
        e.allPackagesListNew = i;
        let r = document.createElement("div");
        r.className = "referencesListColEnabled";
        r.innerText = "";
        o.appendChild(r);
        let s = document.createElement("div");
        s.className = "referencesListColName2";
        o.appendChild(s);
        let a = document.createElement("span");
        a.className = "referenceSearchButton2";
        s.appendChild(a);
        let l = document.createElement("input");
        l.className = "referencesSearchBox";
        l.text = "Search...";
        l.type = "text";
        l.onkeydown = (t) => {
          if (t.key == "Escape") {
            l.value = e.cachedSearchBoxValueBefore;
            l.oninput();
          } else if (t.key == "Enter") {
          }
        };
        l.oninput = (t) => {
          i.innerHTML = "";
          e.HighlightAfterToggle = null;
          configEditor_refreshUI(e);
          if (l.value.length) {
          } else {
          }
        };
        l.onblur = () => {};
        e.filterPackages = l;
        s.appendChild(l);
        a.onclick = () => {
          if (l.className === "referencesSearchBoxTransparent") {
            l.className = "referencesSearchBox";
            l.focus();
            l.select();
            e.cachedSearchBoxValueBefore = l.value;
          } else {
            l.className = "referencesSearchBoxTransparent";
          }
        };
        let d = document.createElement("div");
        d.className = "referencesListColSymbol";
        d.innerText = "Library Symbol";
        o.appendChild(d);
        let c = document.createElement("div");
        c.className = "referencesListColVersion";
        c.innerText = "Version";
        o.appendChild(c);
        let u = document.createElement("div");
        u.className = "referencesListColPublisher";
        u.innerText = "Publisher";
        u.title = u.innerText;
        o.appendChild(u);
        let p = document.createElement("div");
        p.className = "referencesListColPaths";
        p.innerText = "Path";
        o.appendChild(p);
        let f = document.createElement("div");
        f.className = "referencesListColLibraryID";
        f.innerText = "LibraryID";
        o.appendChild(f);
        let g = document.createElement("div");
        g.className = "referencesListColLocale";
        g.innerText = "Locale";
        o.appendChild(g);
        let m = document.createElement("div");
        m.className = "referencesListColLicence";
        m.innerText = "Licence";
        m.title = m.innerText;
        o.appendChild(m);
        let h = document.createElement("div");
        h.className = "referencesListColPublishedDate";
        h.innerText = "Date";
        h.title = h.innerText;
        o.appendChild(h);
      }
      t.setValue = (t) => SetReferences(e, t);
      var g = document.createElement("div");
      g.className = t.id + "_LoadFromFileDiv optionLoadFromFileDiv";
      n.appendChild(g);
      e.notLoggedInWarning = document.createElement("div");
      e.notLoggedInWarning.className = "warningNotLoggedIn";
      e.notLoggedInWarning.innerHTML =
        "⚠ 提示：登录以查看您创建的任何私有包";
      e.notLoggedInWarning.onclick = () => {
        modalDialogAfterCloseAction = () => {
          e.vscode.postMessage({ type: "getOnlinePackages" });
          configEditor_refreshUI(e);
        };
        packageManagerPanel.showSignInForm(() => {});
      };
      n.appendChild(e.notLoggedInWarning);
      n.appendChild(document.createElement("br"));
      var m = document.createElement("div");
      m.className = t.id + "_LoadFromFileDiv optionLoadFromFileDiv";
      n.appendChild(m);
      buttonDiv = document.createElement("button");
      buttonDiv.className = "loadFromFile";
      buttonDiv.innerHTML = "从文件导入...";
      buttonDiv.onclick = (t) => {
        if (e.referencesListMode == 1) {
          e.vscode.postMessage({ type: "referenceLoadFromFile" });
        } else {
          e.vscode.postMessage({ type: "packageLoadFromFile" });
        }
      };
      m.appendChild(buttonDiv);
    } else {
      var h = t.values.split(",");
      if (t.filterValues) {
        h = h.filter((o) => t.filterValues(e.configData, o));
      }
      var u = document.createElement("select");
      u.className = t.id + "_SELECT optionContentInner";
      u.onkeydown = (t) => HTMLSelectKeypressHandler(e, t);
      h.forEach((e) => {
        var t = document.createElement("option");
        t.innerHTML = e;
        u.options.add(t);
      });
      l.appendChild(u);
      t.contentInnerDiv = u;
      var v = document.createElement("div");
      l.appendChild(v);
      u.oninput = (o) => {
        changeOption(e, t.id, h[u.selectedIndex]);
        a.classList.add("animateHiddenOff");
      };
      t.setValue = (e) => {
        var t = h.findIndex((t) => e?.toLowerCase() === t?.toLowerCase());
        if (t == -1) {
          if (e) {
            v.innerText = "INVALID VALUE: '" + e + "'";
            v.className = "invalidOptionConfigValue";
          }
          u.selectedIndex = -1;
        } else {
          u.selectedIndex = t;
        }
      };
      if (t.validate === undefined) {
        t.validate = (e) => {
          if (e !== undefined && !h.includes(e)) {
            return `invalid value`;
          }
          return true;
        };
      }
      t.inputElement = u;
    }
    e.optionsContainer.appendChild(n);
    var y = document.createElement("div");
    y.className = t.id + "_ERRORS optionErrors";
    n.appendChild(y);
    t.errorsDiv = y;
    i.oninput = () => {
      if (i.checked) {
        t.inputElement.disabled = false;
        t.inputElement.focus();
        e.configData[t.id] = e.inheritedConfigData[t.id];
        if (t.firstEnabled !== undefined) {
          e.configData[t.id] = t.firstEnabled();
        }
        configDataUpdated(e);
      } else {
        removeOption(e, t.id);
        t.inputElement.disabled = true;
      }
      configEditor_refreshUI(e);
      a.classList.add("animateHiddenOff");
    };
  });
  e.errorContainer = document.createElement("div");
  e.rootElement.appendChild(e.errorContainer);
  e.errorContainer.className = "error";
  e.errorContainer.style.display = "none";
}
function SetReferences(e, t) {
  var o = 0;
  var n = JSON.stringify(e.HighlightAfterToggle);
  e.HighlightAfterToggle = null;
  if (e.configData["project.settingsVersion"] === undefined) {
    e.configData["project.settingsVersion"] = 0;
  }
  if (e.configData["project.settingsVersion"] < 1) {
    let o = 0;
    let n = false;
    let r = undefined;
    t.forEach((e) => {
      o++;
      if (e.id === "{F50B82D0-DCAB-43FE-9631-11959D4A4728}") {
        r = o;
        e.hasBeenSplit = true;
      } else if (e.id === "{D63CB78D-9F5B-42FE-B94C-A545F2B2BFC3}") {
        n = true;
      }
      return true;
    });
    if (r && !n) {
      var i = { id: "{D63CB78D-9F5B-42FE-B94C-A545F2B2BFC3}" };
      t.splice(r, 0, i);
    }
    e.configData["project.settingsVersion"] = 1;
  }
  e.internalPackages.forEach((e) => {
    var o = t.find((t) => t.id === e.id);
    var n = o !== undefined;
    if (n) {
      o.name = e.name;
      o.versionMajor = e.versionMajor;
      o.versionMinor = e.versionMinor;
      o.versionRevision = e.versionRevision;
      o.versionBuild = e.versionBuild;
      o.publisher = "TWINBASIC-COMPILER";
      o.licence = e.licence;
      o.isCompilerPackage = true;
    }
  });
  var r = [
    {
      id: "{54F90FBF-5CDC-41D6-AEC2-983DEF203B07}",
      name: "[COMPILER PACKAGE] twinBASIC - VBA Compatibility Package",
      symbolId: "VBA",
      path32: "/Packages/VBA",
      path64: "/Packages/VBA",
      versionMajor: 0,
      versionMinor: 0,
      versionBuild: 0,
      versionRevision: 1,
      isNonMovable: true,
      isDisabled: e.configData["project.disablePackageVBA"] ? true : false,
    },
    {
      id: "{8BEB50D8-B4BB-44C7-9784-35AF50ABC872}",
      name: "[COMPILER PACKAGE] twinBASIC - VBRUN Compatibility Package",
      symbolId: "VBRUN",
      path32: "/Packages/VBRUN",
      path64: "/Packages/VBRUN",
      versionMajor: 0,
      versionMinor: 0,
      versionBuild: 0,
      versionRevision: 1,
      isNonMovable: true,
      isDisabled: e.configData["project.disablePackageVBRUN"] ? true : false,
    },
  ];
  let s = r.length;
  r.push(...t);
  e.referencesListNew.innerHTML = "";
  var a = 0;
  r.forEach((i) => {
    if (i.id === "{EA18E2B1-80BA-478D-AC7C-E955E6AA1B05}") {
      i.name = "[twinBASIC Extension] Custom Controls DESIGNER Library";
    }
    var r = document.createElement("option");
    r.className = i.id;
    r.value = i.name;
    var l = "";
    if (i.versionRevision) {
      l =
        "." +
        i.versionBuild +
        "." +
        i.versionRevision +
        ", " +
        i.licence +
        " licence, by " +
        i.publisher;
    }
    var d = false;
    problemReferences.forEach((e) => {
      if (
        e.problemRefDescription === i.name &&
        e.problemRefVerMajor == i.versionMajor &&
        e.problemRefVerMinor == i.versionMinor
      ) {
        d = true;
      }
    });
    var c = JSON.stringify(i);
    if (c === n) {
      o = e.referencesSelect.options.length;
    }
    {
      let o =
        i.name &&
        (i.name.indexOf("[COMPILER PACKAGE]") === 0 ||
          i.name.indexOf("[twinBASIC Extension]") === 0);
      var u = document.createElement("div");
      u.className = "referencesListRow";
      e.referencesListNew.appendChild(u);
      let n = document.createElement("div");
      n.className = "referencesListColEnabled";
      n.innerHTML = "<div class='tickIcon2'></div>";
      u.appendChild(n);
      if (i.isDisabled) {
        n.innerHTML = "<div class='tickIcon2empty'></div>";
      }
      n.onclick = () => {
        reference_toggle(e, i, true);
      };
      let r = document.createElement("div");
      r.className = "referencesListColName";
      r.title = o
        ? i.name
            .replace("[COMPILER PACKAGE] ", "")
            .replace("[twinBASIC Extension] ", "")
        : i.name;
      r.innerText = r.title;
      u.appendChild(r);
      let l = document.createElement("div");
      l.className = "referencesListColMove";
      u.appendChild(l);
      let c = a - s;
      if (!i.isNonMovable) {
        let o = document.createElement("div");
        o.className = "pinkArrowDown";
        if (c === t.length - 1) o.className += " disabled2";
        o.title = "Move this reference down the list, giving it LOWER priority";
        l.appendChild(o);
        o.onclick = (t) => {
          reference_moveDown(e, i, c);
        };
        let n = document.createElement("div");
        n.className = "pinkArrowUp";
        if (c === 0) n.className += " disabled2";
        n.title = "Move this reference up the list, giving it HIGHER priority";
        l.appendChild(n);
        n.onclick = (t) => {
          reference_moveUp(e, i, c);
        };
      }
      if (d) {
        let e = document.createElement("div");
        e.className = "referencesListError";
        e.innerHTML = "⚠ ERROR unable to load this reference &nbsp; &nbsp;";
        e.title =
          "An error occured in trying to load this reference.  Press 'FIX' to try to correct the problem.";
        r.appendChild(e);
        let t = document.createElement("div");
        t.className = "errorFixClickable";
        t.innerText = "FIX";
        e.appendChild(t);
        t.onclick = () => {
          showModalNotification(
            "Sorry, this feature is not yet implemented.\n\nFor now, please remove the reference manually, and\nadd it again from the '可用的COM引用' list"
          );
        };
      }
      let g = document.createElement("div");
      g.className = "referencesListColSymbol";
      let m = document.createElement("div");
      m.className = "referencesListColSymbolInner";
      m.innerText = "...";
      g.appendChild(m);
      if (i.symbolId !== undefined) {
        if (i.id === "{F50B82D0-DCAB-43FE-9631-11959D4A4728}") {
          i.symbolId = "VB";
        }
        m.innerText = i.symbolId;
      } else {
        if (i.id === "{D63CB78D-9F5B-42FE-B94C-A545F2B2BFC3}") {
          m.innerText = "Win原生公共控件";
        } else {
          var p = e.uniqueSymbolRequestId++;
          e.symbolRequests[p] = m;
          m.element = i;
          librarySymbolRequest(e, p, i);
        }
      }
      if (i.versionRevision === undefined) {
        let t = document.createElement("div");
        t.className = "referencesListColSymbolEditLink";
        t.innerText = "🖉";
        t.title =
          "Click here to customize the library symbol used in this project";
        g.appendChild(t);
        t.onclick = () => {
          let o = document.createElement("div");
          o.className = "referencesListColSymbolEdit";
          t.appendChild(o);
          let n = document.createElement("input");
          n.className = "referencesListColSymbolEditInput";
          o.appendChild(n);
          let r = i.overrideSymbol
            ? i.overrideSymbol
            : i.symbolId
            ? i.symbolId
            : "";
          n.value = r;
          n.focus();
          n.onkeydown = (e) => {
            if (e.which === 32) return false;
            if (e.key === "Enter") n.blur();
            if (e.key === "Escape") {
              n.value = r;
              n.blur();
            }
          };
          n.onblur = (t) => {
            debugger;
            if (n.value.length > 0 && n.value !== i.symbolId) {
              e.configData["project.references"][c].overrideSymbol = n.value;
            } else {
              e.configData["project.references"][c].overrideSymbol = undefined;
            }
            configDataUpdated(e);
            configEditor_refreshUI(e);
          };
          n.onclick = (e) => {
            e.stopPropagation();
          };
        };
      }
      if (i.overrideSymbol) {
        m.classList.add("strikethru");
        let e = document.createElement("div");
        e.className = "referencesListColSymbolOverride";
        e.innerText = i.overrideSymbol;
        g.appendChild(e);
      }
      u.appendChild(g);
      let h = document.createElement("div");
      h.className = "referencesListColVersion";
      if (i.versionRevision !== undefined) {
        h.innerText =
          i.versionMajor +
          "." +
          i.versionMinor +
          "." +
          i.versionBuild +
          "." +
          i.versionRevision;
      } else {
        h.innerText = i.versionMajor + "." + i.versionMinor;
      }
      u.appendChild(h);
      let v = document.createElement("div");
      v.className = "referencesListColPublisher";
      v.innerText = o ? "[BUILT-IN]" : i.publisher ? i.publisher : "";
      v.title = v.innerText;
      u.appendChild(v);
      let y = document.createElement("div");
      y.className = "referencesListColPaths";
      if (i.path32 === i.path64) {
        y.innerText = i.path32 ? i.path32 : "";
      } else {
        let e = "";
        if (i.path32 !== undefined && i.path32 !== "") {
          y.innerText = i.path32;
          e = y.innerText;
        }
        let t = "";
        if (i.path64 !== undefined && i.path64 !== "") {
          y.innerText = i.path64;
          t = y.innerText;
        }
        y.innerHTML =
          (e ? "<b>win32: </b>" + e : "") +
          (e && t ? "<br/>" : "") +
          (t ? "<b>win64: </b>" + t : "");
      }
      y.title = y.innerText;
      u.appendChild(y);
      let b = document.createElement("div");
      b.className = "referencesListColLibraryID";
      b.innerText = i.id;
      b.title = b.innerText;
      u.appendChild(b);
      let C = document.createElement("div");
      C.className = "referencesListColLocale";
      C.innerText = i.lcid ? i.lcid : "";
      u.appendChild(C);
      let E = document.createElement("div");
      E.className = "referencesListColLicence";
      E.innerText = i.licence ? i.licence : "";
      E.title = E.innerText;
      u.appendChild(E);
      let I = document.createElement("div");
      I.className = "referencesListColPublishedDate";
      I.innerText = i.publishedDate ? i.publishedDate : "";
      I.title = I.innerText;
      u.appendChild(I);
      let D = document.createElement("div");
      D.className = "referencesListColUseActiveXControls";
      var f = false;
      if (i.useActiveXControls === undefined || i.useActiveXControls) {
        D.innerHTML = "<div class='tickIcon2'></div>";
        f = true;
      } else {
        D.innerHTML = "<div class='tickIcon2empty'></div>";
      }
      u.appendChild(D);
      D.onclick = () => {
        e.configData["project.references"][c].useActiveXControls = !f;
        configDataUpdated(e);
        configEditor_refreshUI(e);
      };
    }
    a++;
  });
  var l = e.filter.value.toLowerCase();
  if (l === "") l = null;
  e.notLoggedInWarning.style = "display: none";
  if (e.referencesListMode === 1) {
    e.typeLibrariesAvailable.forEach((o) => {
      var n =
        t.find(
          (e) =>
            e.id === o.id &&
            e.versionMajor === o.versionMajor &&
            e.versionMinor === o.versionMinor &&
            e.lcid === o.lcid &&
            (e.overrideSymbol === undefined || e.overrideSymbol == "")
        ) != undefined;
      if (l === null || o.name.toLowerCase().includes(l)) {
        {
          let t = o.name.indexOf("[twinBASIC Extension]") === 0;
          var i = document.createElement("div");
          i.className = "referencesListRow";
          e.allReferencesListNew.appendChild(i);
          let r = document.createElement("div");
          r.className = "referencesListColEnabled";
          if (n) {
            r.innerHTML = "<div class='tickIcon2'></div>";
          } else {
            r.innerHTML = "<div class='tickIcon2empty'></div>";
          }
          r.onclick = () => {
            reference_toggle(e, o, n);
            n = !n;
            if (n) {
              r.innerHTML = "<div class='tickIcon2'></div>";
            } else {
              r.innerHTML = "<div class='tickIcon2empty'></div>";
            }
          };
          i.appendChild(r);
          let s = document.createElement("div");
          s.className = "referencesListColName2";
          s.title = t ? o.name.replace("[twinBASIC Extension] ", "") : o.name;
          s.innerText = s.title;
          i.appendChild(s);
          let a = document.createElement("div");
          a.className = "referencesListColSymbol";
          a.innerText = "...";
          if (o.symbolId !== undefined) {
            a.innerText = o.symbolId;
          } else {
            a.classList.add("clickable");
            a.onclick = () => {
              var t = e.uniqueSymbolRequestId++;
              e.symbolRequests[t] = a;
              librarySymbolRequest(e, t, o);
            };
          }
          i.appendChild(a);
          let l = document.createElement("div");
          l.className = "referencesListColVersion";
          if (o.versionRevision !== undefined) {
            l.innerText =
              o.versionMajor +
              "." +
              o.versionMinor +
              "." +
              o.versionBuild +
              "." +
              o.versionRevision;
          } else {
            l.innerText = o.versionMajor + "." + o.versionMinor;
          }
          i.appendChild(l);
          let d = document.createElement("div");
          d.className = "referencesListColPublisher";
          d.innerText = t ? "[BUILT-IN]" : o.publisher ? o.publisher : "";
          d.title = d.innerText;
          i.appendChild(d);
          let c = document.createElement("div");
          c.className = "referencesListColPaths";
          if (o.path32 === o.path64) {
            c.innerText = o.path32 ? o.path32 : "";
          } else {
            let e = "";
            if (o.path32 !== undefined && o.path32 !== "") {
              c.innerText = o.path32;
              e = c.innerText;
            }
            let t = "";
            if (o.path64 !== undefined && o.path64 !== "") {
              c.innerText = o.path64;
              t = c.innerText;
            }
            c.innerHTML =
              (e ? "<b>win32: </b>" + e : "") +
              (e && t ? "<br/>" : "") +
              (t ? "<b>win64: </b>" + t : "");
          }
          c.title = c.innerText;
          i.appendChild(c);
          let u = document.createElement("div");
          u.className = "referencesListColLibraryID";
          u.innerText = o.id;
          u.title = u.innerText;
          i.appendChild(u);
          let p = document.createElement("div");
          p.className = "referencesListColLocale";
          p.innerText = o.lcid ? o.lcid : "";
          i.appendChild(p);
          let f = document.createElement("div");
          f.className = "referencesListColLicence";
          f.innerText = o.licence ? o.licence : "";
          f.title = f.innerText;
          i.appendChild(f);
          let g = document.createElement("div");
          g.className = "referencesListColPublishedDate";
          g.innerText = o.publishedDate ? o.publishedDate : "";
          g.title = g.innerText;
          i.appendChild(g);
        }
      }
    });
  } else if (e.referencesListMode === 2) {
    e.arrayOfOptions = [];
    e.installedPackages.forEach((o) => {
      var n =
        t.find(
          (e) =>
            e.id === o.id &&
            e.versionMajor === o.versionMajor &&
            e.versionMinor === o.versionMinor &&
            e.versionRevision === o.versionRevision &&
            e.versionBuild === o.versionBuild &&
            e.lcid === o.lcid
        ) != undefined;
      if (l === null || o.name.toLowerCase().includes(l)) {
        e.arrayOfOptions.push(createNewListEntryPackage(e, o, n));
      }
    });
    e.internalPackages.forEach((o) => {
      var n = t.find((e) => e.id === o.id);
      var i = n !== undefined;
      if (l === null || o.name.toLowerCase().includes(l)) {
        e.arrayOfOptions.push(createNewListEntryPackage(e, o, i));
      }
    });
    e.allPackagesListNew.innerHTML = "";
    e.onlinePackages.public.forEach((t) => parsePackage(e, t, false, l));
    e.onlinePackages.private.forEach((t) => parsePackage(e, t, true, l));
    e.arrayOfOptions.sort(function (e, t) {
      return e.refName.localeCompare(t.refName);
    });
    e.arrayOfOptions.forEach(function (t) {
      if (t) e.allPackagesListNew.appendChild(t);
    });
    if (e.onlinePackages.loggedIn == true) {
      e.notLoggedInWarning.style = "display: none";
    } else {
      e.notLoggedInWarning.style = "";
    }
  }
  if (o !== 0) {
    e.referencesSelect.focus();
    e.referencesSelect.scroll(0, 0);
    e.referencesSelect.selectedIndex = o - 1;
    e.moveReferenceUp.disabled = false;
    e.moveReferenceDown.disabled = false;
  }
}
function parsePackage(e, t, o, n) {
  var i = t.versions[0];
  {
    var r = false;
    var s = {
      id: t.projectId,
      symbolId: i.symbol,
      name: (o ? "[PRIVATE] " : "") + i.description,
      versionMajor: i.versionMajor,
      versionMinor: i.versionMinor,
      versionRevision: i.versionRevision,
      versionBuild: i.versionBuild,
      isOnlinePackage: true,
      licence: i.licence,
      publisher: t.publisher,
      publishedDate: i.publishedDate,
      publishedTime: i.publishedTime,
    };
    var a = e.internalPackages.find((e) => e.id === s.id);
    if (a !== undefined) {
      return;
    }
    var l = e.installedPackages.find(
      (e) =>
        e.id === s.id &&
        e.versionMajor === s.versionMajor &&
        e.versionMinor === s.versionMinor &&
        e.versionRevision === s.versionRevision &&
        e.versionBuild === s.versionBuild
    );
    if (l !== undefined) {
      l.publisher = s.publisher;
      l.publishedDate = s.publishedDate;
      l.publishedTime = s.publishedTime;
      if (l.htmlOpt) {
        var d = JSON.stringify(l);
        l.htmlOpt.setAttribute("customInfo_Object", d);
        r = l.htmlOpt.getAttribute("customInfo_IsEnabled") == "true";
        l.htmlOpt.innerHTML =
          (r ? "&#x2611 " : "&#x2610 ") +
          l.name +
          " &nbsp; [v" +
          l.versionMajor +
          "." +
          l.versionMinor +
          "." +
          l.versionBuild +
          "." +
          l.versionRevision +
          ", " +
          l.licence +
          " licence, by " +
          l.publisher +
          "]";
      }
    } else {
      if (n === null || s.name.toLowerCase().includes(n)) {
        e.arrayOfOptions.push(createNewListEntryPackage(e, s, r));
      }
    }
  }
}
function createNewListEntryPackage(e, t, o) {
  let n = t.name.indexOf("[COMPILER PACKAGE]") === 0;
  var i = document.createElement("div");
  i.className = "referencesListRow";
  let r = document.createElement("div");
  r.className = "referencesListColEnabled";
  if (o) {
    r.innerHTML = "<div class='tickIcon2'></div>";
  } else {
    r.innerHTML = "<div class='tickIcon2empty'></div>";
  }
  r.onclick = () => {
    reference_toggle(e, t, o);
    o = !o;
    r.innerHTML = "<div class='tickIconInProgress'></div>";
  };
  i.appendChild(r);
  let s = document.createElement("div");
  s.className = "referencesListColName2";
  s.title = n ? t.name.replace("[COMPILER PACKAGE] ", "") : t.name;
  s.innerText = s.title;
  i.appendChild(s);
  let a = document.createElement("div");
  a.className = "referencesListColSymbol";
  a.innerText = "...";
  if (t.symbolId !== undefined) a.innerText = t.symbolId;
  i.appendChild(a);
  let l = document.createElement("div");
  l.className = "referencesListColVersion";
  if (t.versionRevision !== undefined) {
    l.innerText =
      t.versionMajor +
      "." +
      t.versionMinor +
      "." +
      t.versionBuild +
      "." +
      t.versionRevision;
  } else {
    l.innerText = t.versionMajor + "." + t.versionMinor;
  }
  i.appendChild(l);
  let d = document.createElement("div");
  d.className = "referencesListColPublisher";
  d.innerText = n ? "[BUILT-IN]" : t.publisher ? t.publisher : "";
  d.title = d.innerText;
  i.appendChild(d);
  let c = document.createElement("div");
  c.className = "referencesListColPaths";
  if (t.path32 === t.path64) {
    c.innerText = t.path32 ? t.path32 : "";
  } else {
    let e = "";
    if (t.path32 !== undefined && t.path32 !== "") {
      c.innerText = t.path32;
      e = c.innerText;
    }
    let o = "";
    if (t.path64 !== undefined && t.path64 !== "") {
      c.innerText = t.path64;
      o = c.innerText;
    }
    c.innerHTML =
      (e ? "<b>win32: </b>" + e : "") +
      (e && o ? "<br/>" : "") +
      (o ? "<b>win64: </b>" + o : "");
  }
  c.title = c.innerText;
  i.appendChild(c);
  let u = document.createElement("div");
  u.className = "referencesListColLibraryID";
  u.innerText = t.id;
  u.title = u.innerText;
  i.appendChild(u);
  let p = document.createElement("div");
  p.className = "referencesListColLocale";
  p.innerText = t.lcid ? t.lcid : "";
  i.appendChild(p);
  let f = document.createElement("div");
  f.className = "referencesListColLicence";
  f.innerText = t.licence ? t.licence : "";
  f.title = f.innerText;
  i.appendChild(f);
  let g = document.createElement("div");
  g.className = "referencesListColPublishedDate";
  g.innerText = t.publishedDate ? t.publishedDate : "";
  g.title = g.innerText;
  i.appendChild(g);
  i.refName = t.name;
  return i;
}
function removeOptions(e, t) {
  var o,
    n = t.options.length - 1;
  for (o = n; o >= 0; o--) {
    t.remove(o);
  }
}
function configEditor_refreshUI(e) {
  if (e.referencesSelect !== undefined) {
    removeOptions(e, e.referencesSelect);
    removeOptions(e, e.referencesAvailable);
  }
  var t = e.configData["configuration.inherits"];
  e.inheritedConfigData = undefined;
  e.allConfigs.forEach((o) => {
    if (o["configuration.name"] == t) {
      e.inheritedConfigData = o;
    }
  });
  e.schema.forEach((t) => {
    if (t.rootDiv) {
      if (e.configData.hasOwnProperty(t.id)) {
        t.rootDiv.className = "optionEnabled";
        t.enablerDiv.checked = true;
        t.setValue(e.configData[t.id]);
        if (t.inputElement) t.inputElement.disabled = false;
      } else {
        t.rootDiv.className = "optionDisabled";
        t.enablerDiv.checked = false;
        if (t.inputElement) t.inputElement.disabled = true;
        if (e.inheritedConfigData !== undefined)
          t.setValue(e.inheritedConfigData[t.id]);
      }
    }
  });
  updateCssVars(e);
}
function configEditor_debugMsg(e, t) {
  e.vscode.postMessage({ type: "debugMsg", args: [t] });
}
function configEditor_init(e, t, o, n, i) {
  e.vscode.postMessage({ type: "getAvailableTypeLibrariesData" });
  e.schema = JSONfn_parse(t);
  e.configData = o;
  e.allConfigs = n;
  e.warningsTable = i;
  if (e.configData["configuration.inherits"] === undefined) {
    e.configData["configuration.inherits"] = "Defaults";
  }
  if (e.configData["project.warnings"] === undefined) {
    e.configData["project.warnings"] = { ignored: [], errors: [] };
  }
  if (e.configData["project.id"] === "{00000000-0000-0000-0000-000000000000}") {
    e.configData["project.id"] = generateUUID();
  }
  e.initialHTML = e.rootElement.innerHTML;
  configEditor_initUIHeader(e);
  configEditor_initUI(e);
  configEditor_refreshUI(e);
  doValidation(e);
  if (e.afterInitCallback) e.afterInitCallback();
}
function configEditor_applyFilter(e, t) {
  e.CurrentFilter = t;
  configEditor_initUIHeader(e);
  configEditor_initUI(e);
  configEditor_refreshUI(e);
}
function configEditor_gotOnlinePackages(e, t) {
  e.onlinePackages = t;
  configEditor_refreshUI(e);
}
function configEditor_gotAvailableTypeLibrariesData(e, t, o, n, i) {
  e.typeLibrariesAvailable = t;
  e.installedPackages = n;
  e.internalPackages = i;
  configEditor_refreshUI(e);
  if (o) {
    o = o.toLowerCase();
    e.typeLibrariesAvailable.forEach((t) => {
      if (t.path32) {
        if (
          t.path32.toLowerCase() == o ||
          t.path32.toLowerCase().substring(0, o.length + 1) == o + "\\"
        ) {
          reference_toggle(e, t, false);
        }
      }
    });
    e.installedPackages.forEach((t) => {
      if (t.path32) {
        if (
          t.path32.toLowerCase() == o ||
          t.path32.toLowerCase().substring(0, o.length + 1) == o + "\\"
        ) {
          reference_toggle(e, t, false);
        }
      }
    });
  }
}
function configEditor_librarySymbolResponse(e, t, o) {
  _librarySymbolResponse(e, t, o);
}
var statusDebuggerOuter;
var statusDebugger;
var latestFileSystemInMemory;
var addinAlterationsAdditions = [];
var compilerStatus;
var compilerStatusOuter;
var compilerLicence;
var compilerLicenceOuter;
function removeAddinAlterations() {
  addinAlterationsAdditions.forEach((e) => {
    e.parentNode.removeChild(e);
  });
  addinAlterationsAdditions = [];
  removeAllToolWindows();
  unregisterAddInKeyboardShortcuts();
}
function initConnectionManager() {
  compilerStatus = document.getElementById("compilerStatus");
  compilerStatusOuter = document.getElementById("compilerStatusOuter");
  compilerLicence = document.getElementById("compilerLicence");
  compilerLicenceOuter = document.getElementById("compilerLicenceOuter");
  compilerLicenceOuter.onclick = onChangeLicence;
}
function getConnectionState(e, t) {
  const o = 0;
  const n = 1;
  const i = 2;
  const r = 3;
  var s;
  var a = false;
  if (e && e.webSocket) {
    if (e.webSocket.hasErrored) {
      s = t + ": Error occured";
      a = true;
    } else {
      switch (e.webSocket.socket.readyState) {
        case o:
          s = t + ": Connecting";
          break;
        case n:
          break;
        case i:
          s = t + ": Disconnecting";
          break;
        case r:
          s = t + ": Disconnected";
          a = true;
          break;
        default:
          s = t + ": UNKNOWN-STATE";
      }
    }
  } else {
    s = t + ": Not initialized";
    a = true;
  }
  return { stateInfo: s, isDisconnected: a };
}
function connectionStateChanged() {
  var e = getConnectionState(root, "COMPILER");
  var t = "";
  var o = 0;
  if (e.stateInfo) {
    t += (t.length > 0 ? "\n" : "") + e.stateInfo;
  } else {
    o++;
    t += (t.length > 0 ? "\n" : "") + "COMPILER: OPERATIONAL";
  }
  var n = getConnectionState(fs, "FS");
  if (n.stateInfo) {
    t += (t.length > 0 ? "\n" : "") + n.stateInfo;
  } else {
    o++;
    t += (t.length > 0 ? "\n" : "") + "FS: OPERATIONAL";
  }
  var i = getConnectionState(lspSocket, "LSP");
  if (i.stateInfo) {
    t += (t.length > 0 ? "\n" : "") + i.stateInfo;
  } else {
    o++;
    t += (t.length > 0 ? "\n" : "") + "LSP: OPERATIONAL";
  }
  var r = getConnectionState(debugSocket, "DEBUGGER");
  if (r.stateInfo) {
    t += (t.length > 0 ? "\n" : "") + r.stateInfo;
  } else {
    o++;
    t += (t.length > 0 ? "\n" : "") + "DEBUGGER: OPERATIONAL";
  }
  if (o < 4) {
    if (o > 0) {
      compilerStatus.innerText = "tB Services: LIMITED";
      compilerStatusOuter.classList.add("servicesPARTIAL");
      compilerStatusOuter.classList.remove("servicesOK");
    } else {
      compilerStatus.innerText = "tB Services: UNAVAILABLE";
      compilerStatusOuter.classList.remove("servicesPARTIAL");
      compilerStatusOuter.classList.remove("servicesOK");
    }
  } else {
    compilerStatus.innerText = "tB Services: OPERATIONAL";
    compilerStatusOuter.classList.remove("servicesPARTIAL");
    compilerStatusOuter.classList.add("servicesOK");
  }
  compilerStatusOuter.title = t;
  if (
    e.isDisconnected &&
    n.isDisconnected &&
    i.isDisconnected &&
    r.isDisconnected
  ) {
    restartCompiler();
  }
}
function projectClosed() {
  if (onCloseProjectComplete) {
    try {
      openEditors.closeAllTabsNoSave();
      onCloseProjectComplete();
    } catch (e) {}
    onCloseProjectComplete = undefined;
  }
  isClosingProject = false;
  projectIsLoaded = false;
}
function restartCompiler() {
  if (!compilerPassKey) return;
  if (isDebugMode) {
    hostAppObject.CloseWindow("ignore");
    return;
  }
  fs.tree.clear();
  outlinePanel.tree.view.data.clear();
  if (buildConfigSelector.value !== "nocompile") {
    problemsPanel.tree.view.data.clear();
  }
  callStackPanel.tree.clear();
  variablesPanel.tree.clear();
  watchPanel.tree.clear();
  historyPanel.tree.clear();
  packageManagerPanel.hide();
  statusMemUsageDiv.classList.add("hide");
  closeAllToolWindows();
  removeAddinAlterations();
  editorHistoryLinks = [];
  fs.tree.rootFolder.cachedDiagnostics_childErrorCount = 0;
  fs.tree.rootFolder.cachedDiagnostics_childWarningCount = 0;
  errorCountDiv.innerText = "0";
  warningCountDiv.innerText = "0";
  runningProcessesContainer.innerHTML = "";
  try {
    clearDebuggingCallframe();
  } catch (e) {}
  var e = root;
  root = new _RootConnection();
  if (isClosingProject) {
    isClosingProject = false;
    openEditors.closeAllExcept(undefined, false, true);
    clearDebugConsole();
    projectFilePath = undefined;
    rootMenuText.innerText = "";
    rootMenuTitleFull.innerText = "";
    projectClosed();
    return;
  }
  isRestarting = true;
  lockUICount = 1;
  unlockUI();
  try {
    e.sendLiveBackupWorkerMessage("getLatestCached", [], (e) => {
      var t = e.data[1];
      latestFileSystemInMemory = t;
      if (t.length > 0) {
        debugOutputLine("restarting from MEMORY [" + projectFilePath + "]");
        root.loadProjectFromMemory(t, projectFilePath);
      } else {
        debugOutputLine("restarting from FILE");
        root.loadProject(projectFilePath);
      }
    });
  } catch (e) {
    syncWait(1e3);
    if (latestFileSystemInMemory && latestFileSystemInMemory.length > 0) {
      debugOutputLine("restarting from MEMORY [" + projectFilePath + "]");
      root.loadProjectFromMemory(latestFileSystemInMemory, projectFilePath);
    } else {
      debugOutputLine("restarting from FILE");
      root.loadProject(projectFilePath);
    }
  }
}
var allCommands = {
  "twinbasic.runCode": {
    handler: (e) => {
      debugOutputLine(
        "Executing '" + e + "'...",
        "debugConsoleEvaluateExecutingText"
      );
      var t = { expression: e };
      if (activeDebuggingFrameId) t.frameId = activeDebuggingFrameId;
      debugSocket.request("evaluate", t, (e) => {
        if (e.message)
          debugOutputLine(e.message, "debugConsoleEvaluateResultText");
      });
    },
  },
  "twinbasic.insertText": {
    handler: (e, t, o) => {
      var n = new monaco.Range(t + 1, o + 1, t + 1, o + 1);
      var i = { major: 1, minor: 1 };
      var r = { identifier: i, range: n, text: e, forceMoveMarkers: true };
      editor.executeEdits("twinbasic", [r]);
    },
  },
};
function registerCommands() {
  Object.keys(allCommands).forEach((e) => {
    allCommands[e].internalId = editor.addCommand(0, (t, o) => {
      allCommands[e].handler(...o);
    });
  });
}
function executeCommand(e, t) {
  var o = allCommands[e];
  if (o) {
    editor.trigger("twinbasic", o.internalId, t);
  }
}
var appOverlay;
var modalDialogContainer;
var lockUICount = 0;
var generalScaling = 1;
var progressLog = undefined;
function initDialog() {
  appOverlay = document.getElementById("appOverlay");
  modalDialogContainer = document.getElementById("modalDialogContainer");
}
function setModalProgressLog(e) {
  if (progressLog) {
    progressLog.innerText = e;
  }
}
function showModalProgressIndicator(e) {
  var t = createDOMElement(undefined, "div", "pleaseWaitDialog", "");
  var o = createDOMElement(t, "div");
  o.id = "progressSpinner";
  if (e) {
    progressLog = createDOMElement(t, "div");
    progressLog.classList = "progressLogMessage";
  }
  showModalDialog(t, undefined, "请稍候...");
}
function hideModalProgressIndicator() {
  progressLog = undefined;
  hideModalDialog();
}
var modalDialogAfterCloseAction = undefined;
function hideModalDialog(e) {
  modalDialogContainer.style.display = "none";
  if (modalDialogAfterCloseAction) {
    var t = modalDialogAfterCloseAction;
    modalDialogAfterCloseAction = undefined;
    t();
  }
  if (!e) unlockUI();
}
function showModalDialog(e, t, o, n, i) {
  if (!i) lockUI(0, undefined);
  modalDialogContainer.innerHTML = "";
  var r;
  var s;
  var a;
  var l;
  var d;
  var c = document.createElement("div");
  c.className = "modalTitleBar";
  c.innerText = o ? o : "twinBASIC";
  c.onpointerdown = (e) => {
    r = modalDialogContainer.offsetLeft;
    s = modalDialogContainer.offsetTop;
    a = e.clientX;
    l = e.clientY;
    c.setPointerCapture(e.pointerId);
    d = true;
  };
  c.onmousemove = (e) => {
    if (d) {
      var t = e.clientX - a;
      var o = e.clientY - l;
      modalDialogContainer.style.left = r + t + "px";
      modalDialogContainer.style.top = s + o + "px";
    }
  };
  c.onpointerup = (e) => {
    d = false;
  };
  modalDialogContainer.appendChild(c);
  if (n) {
    var u = document.createElement("div");
    u.className = "modalTitleBarCloseBtn";
    u.innerHTML = "&nbsp;X&nbsp;";
    u.onpointerdown = (e) => {
      e.stopPropagation();
    };
    u.onmouseup = n;
    u.title = "Close";
    c.appendChild(u);
  }
  modalDialogContainer.appendChild(e);
  modalDialogContainer.style.display = "block";
  modalDialogContainer.tabIndex = 0;
  var p = undefined;
  var f = undefined;
  modalDialogContainer.onkeydown = (e) => {
    if (e.key === "Escape") {
      if (p) p.onclick();
    }
    if (e.key === "Enter") {
      if (f) f.onclick();
    }
  };
  if (t) {
    var g = createDOMElement(modalDialogContainer, "div", "msgBoxButtons");
    var m = createDOMElement(g, "div", "");
    var h = false;
    t.forEach((e) => {
      if (!e.hidden) {
        if (e.caption) {
          var t = createDOMElement(g, "div", "msgBoxButton", e.caption);
          if (e.id) t.id = e.id;
          t.onclick = (t) => {
            if (t.button === 0) e.onclick();
          };
          if (e.width) {
            t.style.width = e.width * generalScaling + "px";
          }
          if (e.isDefaultCancelAction) {
            p = e;
          }
          if (e.isDefaultAcceptAction) {
            f = e;
          }
        } else {
          createDOMElement(g, "div", "msgBoxButtonSpacer");
          h = true;
        }
      }
    });
    if (!h) {
      m.classList = "msgBoxButtonSpacer";
    }
    modalDialogContainer.focus();
  }
  RepositionModalDialog();
}
function RepositionModalDialog() {
  var e = modalDialogContainer.offsetWidth;
  var t = modalDialogContainer.offsetHeight;
  var o = 1;
  if (e > document.body.offsetWidth) {
    debugger;
    o = document.body.offsetWidth / e;
  }
  if (t * o > document.body.offsetHeight) {
    o = document.body.offsetHeight / t;
  }
  if (o !== 1) {
    modalDialogContainer.style.transform = "scale(" + o + ")";
  } else {
    modalDialogContainer.style.transform = "none";
  }
  modalDialogContainer.style.left = (document.body.offsetWidth - e) / 2 + "px";
  modalDialogContainer.style.top = (document.body.offsetHeight - t) / 2 + "px";
}
function lockUI(e, t) {
  lockUICount++;
  appOverlay.style.display = "block";
  appOverlay.style.top = e;
  appOverlay.onclick = t;
}
function unlockUI() {
  if (!lockUICount) return;
  lockUICount--;
  if (lockUICount == 0) {
    appOverlay.style.display = "none";
  }
}
var debugSocket;
const MessageDAPRequest = 0;
var activeDebuggingThreadId = undefined;
var activeDebuggingFrameId = undefined;
var activeDebuggingFileNode = undefined;
var activeDebuggingLine = undefined;
var activeDebuggingError = undefined;
var activeDebuggingSource = undefined;
var activeDebuggingErrorHeader = undefined;
var activeBreakLineDecoration = [];
var activeDebuggingFrameIsTopFrame = false;
var activeBreakLineNumber = -1;
var jumpToLineAction = undefined;
var GlobalFontsList = [];
async function doNagScreen_Xmas2022(e) {
  try {
    var t = await hostAppObject.GetIDESetting("XMAS2022_3");
    if (t == 1) return;
  } catch (e) {}
  e();
  await hostAppObject.SaveIDESetting("XMAS2022_3", 1);
}
function syncActiveBreakLine(e) {
  ignoreAltKey = true;
  setTimeout(() => {
    ignoreAltKey = false;
  }, 300);
  activeBreakLineNumber = e;
  activeBreakLineDecoration = editor.deltaDecorations(
    activeBreakLineDecoration,
    e == -1
      ? []
      : [
          {
            range: new monaco.Range(e, 1, e, 1),
            options: {
              isWholeLine: true,
              className: "activeDebugLineClass",
              glyphMarginClassName: activeDebuggingFrameIsTopFrame
                ? "marginGlyph breakingGlyph"
                : "",
            },
          },
        ]
  );
  if (activeDebuggingError && e != -1) {
    showErrorWidget(e);
  } else {
    hideErrorWidget();
  }
  if (jumpToLineAction) jumpToLineAction.dispose();
  if (e != -1) {
    HostForceFocus();
    jumpToLineAction = editor.addAction({
      id: "jumpToLine",
      label: "设置下一步语句(跳到行)",
      precondition: null,
      keybindingContext: null,
      contextMenuGroupId: "navigation",
      contextMenuOrder: 9999,
      run: function (e) {
        setCurrentThreadExecutionPoint();
      },
    });
  }
}
function setDebuggingCallframe(e, t, o, n, i, r) {
  activeDebuggingThreadId = e;
  activeDebuggingFrameId = t.id;
  activeDebuggingLine = t.line;
  activeDebuggingError = o;
  activeDebuggingSource = n;
  activeDebuggingErrorHeader = i;
  activeDebuggingFrameIsTopFrame = t.isTopFrame;
  var s = fs.tree.resolvePath(t.source.path);
  activeDebuggingFileNode = s;
  if (!liveIDEOptions["previewDocs"]) r = false;
  openEditors.openFile(s, r, false, false, t.line, t.column, undefined, () => {
    if (activeDebuggingFileNode === s) {
      syncActiveBreakLine(activeDebuggingLine);
    } else {
      syncActiveBreakLine(-1);
    }
  });
  variablesPanel.syncVariablesPanelToStackFrame(t);
  watchPanel.evaluateWatches();
}
function clearDebuggingCallframe() {
  syncActiveBreakLine(-1);
  clearDecorations();
  if (activeDebuggingThreadId)
    callStackPanel.clearCallstackInfo(activeDebuggingThreadId);
  variablesPanel.clearVariablesInfo();
  watchPanel.clearWatchResults();
  activeDebuggingFrameId = undefined;
}
class DAPSocket {
  constructor() {
    this.requestsAwaitingResponse = {};
    this.sequenceId = 0;
    this.isConnected = false;
  }
  connect(e, t) {
    this.callback = t;
    this.webSocket = new webSocketJson(
      "ws://localhost:" + e + "/" + compilerPassKey + "/debugger",
      this
    );
    connectionStateChanged();
  }
  onConnected() {
    this.isConnected = true;
    this.callback();
    this.request("threads", {}, (e) => {
      e.body.threads.forEach((e) => {
        callStackPanel.gotThreadInfo(e.id, e.name);
        this.request("stackTrace", { threadId: e.id }, (t) => {
          callStackPanel.gotCallstackInfo(e.id, t);
        });
      });
    });
    if (licenceKey && licenceKey.length >= 84) {
      this.request("x", { type: "LicenceKey", x: licenceKey });
    } else {
      compilerLicence.innerText = "COMMUNITY EDITION";
      compilerLicenceOuter.classList.add("servicesPARTIAL");
      compilerLicenceOuter.classList.remove("servicesOK");
      compilerLicenceOuter.title = compilerLicence.innerText;
    }
    this.request("getFontsList", {}, (e) => {
      GlobalFontsList = e.body.fonts;
      GlobalFontsList.sort();
      GlobalFontsList.reverse();
    });
  }
  updateThreadInfo(e) {
    this.request("threads", { threadId: e }, (e) => {
      e.body.threads.forEach((e) => {
        callStackPanel.gotThreadInfo(e.id, e.name);
      });
    });
  }
  event_stopped(e) {
    this.request("stackTrace", { threadId: e.body.threadId }, (t) => {
      t.body.stackFrames[0].isTopFrame = true;
      setDebuggingCallframe(
        e.body.threadId,
        t.body.stackFrames[0],
        e.body.text,
        e.body.sourceText,
        e.body.headerText,
        true
      );
      callStackPanel.gotCallstackInfo(e.body.threadId, t);
    });
  }
  event_thread(e) {
    this.updateThreadInfo(e.body.threadId);
  }
  event_continued(e) {
    if (e.body.threadId === activeDebuggingThreadId) {
      clearDebuggingCallframe();
    }
  }
  event_output(e) {
    if (e.body.color) {
      if (e.body.color == 16711680) {
        debugOutputPartial(
          e.body.output,
          "debugConsoleOutputTextALERT",
          false,
          e.body.time
        );
      } else if (e.body.color == 16646144) {
        debugOutputPartial(
          e.body.output,
          "debugConsoleOutputTextYELLOW",
          false,
          e.body.time
        );
      } else if (e.body.color == 15395562) {
        debugOutputPartial(
          e.body.output,
          "debugConsoleOutputText",
          true,
          e.body.time
        );
      } else {
        debugOutputPartial(
          e.body.output,
          "debugConsoleOutputText",
          false,
          e.body.time
        );
      }
    } else {
      debugOutputPartial(
        e.body.output,
        e.body.isExecutingHeader
          ? "debugConsoleEvaluateExecutingText"
          : "debugConsoleOutputText",
        false,
        e.body.time
      );
    }
  }
  event_clearDebugConsole(e) {
    clearDebugConsole();
    debugOutputPartial("");
  }
  event_procMonInfo(e) {
    memUsageDiv.innerText = e.body.mem10 / 10;
    userObjectsDiv.innerText = e.body.user;
    gdiObjectsDiv.innerText = e.body.gdi;
  }
  onReceivedObject(e) {
    if (e.type === "response") {
      var t = e.request_seq;
      var o = this.requestsAwaitingResponse[t];
      if (o) {
        delete this.requestsAwaitingResponse[t];
        o(e);
      }
    } else if (e.type === "event") {
      var n = "event_" + e.event;
      var i = this[n];
      if (i) {
        i.call(this, e);
      } else {
        alert("DAP事件: " + e.event.toString());
      }
    } else if (e.type === "request") {
      alert("DAP反向请求: " + e.command.toString());
    } else {
      alert("DAP: 收到错误的通知，没有[type]字段");
    }
  }
  request(e, t, o) {
    this.requestsAwaitingResponse[this.sequenceId] = o;
    this.webSocket.sendObject({
      seq: this.sequenceId++,
      type: "request",
      command: e,
      arguments: t,
    });
  }
  simulateSpaceKey() {
    this.request("simulateSpaceKey", {}, (e) => {});
  }
  changeDebugExecutionLine(e) {
    this.request(
      "setDebugExecutionLine",
      {
        threadId: activeDebuggingThreadId ? activeDebuggingThreadId : -1,
        lineNumber: e,
      },
      (e) => {
        if (e.message) {
          debugOutputLine(e.message);
        }
      }
    );
  }
  continue() {
    clearDebuggingCallframe();
    allowCompilerProcessToSetForegroundWIndow(() => {
      this.request(
        "continue",
        { threadId: activeDebuggingThreadId ? activeDebuggingThreadId : -1 },
        (e) => {
          if (e.message) {
            debugOutputLine(e.message);
          }
        }
      );
    });
  }
  breakInto() {
    this.request(
      "pause",
      { threadId: activeDebuggingThreadId ? activeDebuggingThreadId : -1 },
      (e) => {}
    );
  }
  stop() {
    this.request(
      "terminate",
      { threadId: activeDebuggingThreadId ? activeDebuggingThreadId : -1 },
      (e) => {}
    );
  }
  stepOver() {
    clearDebuggingCallframe();
    this.request(
      "next",
      { threadId: activeDebuggingThreadId ? activeDebuggingThreadId : -1 },
      (e) => {}
    );
  }
  stepInto() {
    clearDebuggingCallframe();
    this.request(
      "stepIn",
      { threadId: activeDebuggingThreadId ? activeDebuggingThreadId : -1 },
      (e) => {}
    );
  }
  stepOut() {
    clearDebuggingCallframe();
    this.request(
      "stepOut",
      { threadId: activeDebuggingThreadId ? activeDebuggingThreadId : -1 },
      (e) => {}
    );
  }
  build(e, t) {
    if (!projectFilePath) {
      var o = createDOMElement(
        undefined,
        "div",
        "simpleMsgBox",
        "您必须首先保存项目。 现在保存？"
      );
      showModalDialog(o, [
        {
          caption: "保存",
          onclick: () => {
            hideModalDialog();
            saveProjectAs();
          },
        },
        {
          caption: "取消",
          onclick: hideModalDialog,
          isDefaultCancelAction: true,
        },
      ]);
      return;
    }
    this.request(
      "doBuild",
      {
        projectFullPath: projectFilePath,
        cleanOnly: e ? e : false,
        ignoreOldBuild: t ? t : false,
      },
      (e) => {}
    );
  }
  findInFiles(e, t, o, n) {
    this.request(
      "findInFiles",
      { search: e, insidePackages: t, matchCase: o, wholeWordOnly: n },
      (t) => {
        if (t.success) {
          displayVirtualFile({
            displayName: "Find in files '" + e + "':",
            html: t.body.results,
            onCreateDom: (e) => {
              const t = e.querySelectorAll(".findResult");
              var o = undefined;
              t.forEach((e) => {
                const t = e;
                t.onclick = () => {
                  if (o) {
                    o.style.backgroundColor = "";
                  }
                  t.style.backgroundColor = "rgb(229 86 86 / 12%)";
                  o = t;
                  var e = fs.tree.resolvePath(
                    "twinbasic:" + t.getAttribute("file")
                  );
                  openEditors.openFile(
                    e,
                    false,
                    false,
                    false,
                    parseInt(t.getAttribute("fileLine")) + 1,
                    parseInt(t.getAttribute("fileLinePos")) + 1
                  );
                };
              });
            },
          });
        }
      }
    );
  }
}
function initDebugSocket() {
  debugSocket = new DAPSocket();
  connectionStateChanged();
}
("use strict");
const WINDOWED_CONTROLS_ZINDEX_OFFSET = 1e6;
var globalShared_ImageRequestId = 0;
function refreshSelectedControlDragPoints(e) {
  e.selectedControls.forEach((t) => {
    showSelectedControlDragPoints(e, t);
  });
}
function isControlLocked(e, t) {
  return e.lockedControls.includes(t);
}
function lockTheControl(e, t, o) {
  var n = unlockTheControl(e, t, true);
  e.lockedControls.push(t);
  refreshSelectedControlDragPoints(e);
  if (!n && !o) IDEOptionsChanged(e);
}
function unlockTheControl(e, t, o) {
  var n = e.lockedControls.length;
  e.lockedControls = e.lockedControls.filter(
    (e) => e.toLowerCase() != t.toLowerCase()
  );
  var i = n != e.lockedControls.length;
  if (i && !o) {
    refreshSelectedControlDragPoints(e);
    IDEOptionsChanged(e);
  }
  return i;
}
function hideDiagonalLine() {
  const e = document.getElementById("lineOuter");
  e.style.visibility = "hidden";
}
function drawDiagonalLine(e, t, o, n) {
  const i = document.getElementById("lineOuter");
  i.style.visibility = "visible";
  const r = document.getElementById("line");
  var s = e - o;
  var a = t - n;
  var l = Math.sqrt(s * s + a * a);
  r.style.width = l + "px";
  r.style.left = e + "px";
  r.style.top = t + "px";
  var d = (Math.atan2(n - t, o - e) * 180) / Math.PI;
  r.style.transform = "rotate(" + d + "deg)";
}
function syncFormDragPoints(e) {
  var t = 0;
  var o = 0;
  var n = 0;
  var i = 0;
  var r = 30;
  var s = 20;
  var a = e.designerContainer.clientHeight - r;
  var l = e.designerContainer.clientWidth - s;
  if (l < 0 || a < 0) return;
  if (!e.designer.isSelected) {
    e.designerDragPointTopLeft.style.visibility = "hidden";
    e.designerDragPointTop.style.visibility = "hidden";
    e.designerDragPointTopRight.style.visibility = "hidden";
    e.designerDragPointLeft.style.visibility = "hidden";
    e.designerDragPointRight.style.visibility = "hidden";
    e.designerDragPointBottomLeft.style.visibility = "hidden";
    e.designerDragPointBottom.style.visibility = "hidden";
    e.designerDragPointBottomRight.style.visibility = "hidden";
  } else {
    e.designerDragPointTopLeft.style.visibility = "visible";
    e.designerDragPointTop.style.visibility = "visible";
    e.designerDragPointTopRight.style.visibility = "visible";
    e.designerDragPointLeft.style.visibility = "visible";
    e.designerDragPointRight.style.visibility = "visible";
    e.designerDragPointBottomLeft.style.visibility = "visible";
    e.designerDragPointBottom.style.visibility = "visible";
    e.designerDragPointBottomRight.style.visibility = "visible";
    e.designerDragPointTopLeft.style.left = o - e.dragPointWidth + "px";
    e.designerDragPointTop.style.left = o + (l - e.dragPointWidth) / 2 + "px";
    e.designerDragPointTopRight.style.left = o + l + "px";
    e.designerDragPointLeft.style.left = o - e.dragPointWidth + "px";
    e.designerDragPointRight.style.left = o + l + "px";
    e.designerDragPointBottomLeft.style.left = o - e.dragPointWidth + "px";
    e.designerDragPointBottom.style.left = o + l / 2 + "px";
    e.designerDragPointBottomRight.style.left = o + l + "px";
    e.designerDragPointTopLeft.style.top = i - e.dragPointHeight + "px";
    e.designerDragPointTop.style.top = i - e.dragPointHeight + "px";
    e.designerDragPointTopRight.style.top = i - e.dragPointHeight + "px";
    e.designerDragPointLeft.style.top = i + a / 2 + "px";
    e.designerDragPointRight.style.top = i + a / 2 + "px";
    e.designerDragPointBottomLeft.style.top = i + a + "px";
    e.designerDragPointBottom.style.top = i + a + "px";
    e.designerDragPointBottomRight.style.top = i + a + "px";
  }
  e.designerDragInfoRight.innerHTML = l + " x " + a;
  e.designerDragInfoRight.style.top = i + (a + 4) + "px";
  e.designerDragInfoRight.style.left =
    o + (l - e.designerDragInfoRight.clientWidth - 15) + "px";
  syncFormDragInfo(e);
}
function syncFormDragInfo(e) {
  var t = e.designer.getBoundingClientRect();
  t = { left: t.left * e.zoomRatio, top: t.top * e.zoomRatio };
  if (e.lastKnownMousePositionX != 0 || e.lastKnownMousePositionY != 0) {
    let o = parseInt(
      (parseInt(e.lastKnownMousePositionX) - parseInt(t.left)) / e.zoomRatio
    );
    let n = parseInt(
      (parseInt(e.lastKnownMousePositionY) - parseInt(t.top)) / e.zoomRatio
    );
    e.designerDragInfoLeft.innerHTML = "x:" + o + " y:" + n;
    e.designerDragInfoLeft.style.top = e.designerDragInfoRight.style.top;
    e.designerDragInfoLeft.style.left = 15 + "px";
    e.designerDragInfoLeft.style.visibility = "visible";
  }
  if (
    e.designerDragInfoLeft.offsetLeft + e.designerDragInfoLeft.offsetWidth >
    e.designerDragInfoRight.offsetLeft
  ) {
    e.designerDragInfoRight.style.top =
      parseInt(e.designerDragInfoRight.style.top) +
      e.designerDragInfoLeft.offsetHeight +
      "px";
  }
  if (e.designerDragInfoRight.offsetLeft < e.designerDragInfoLeft.offsetLeft) {
    e.designerDragInfoRight.style.left = e.designerDragInfoLeft.style.left;
  }
}
function removeSelectedControlDragPoints(e, t) {
  t.classList.remove("hasLockedIcon");
  if (t.draggerTopLeft !== undefined) {
    t.draggerTopLeft.parentElement.removeChild(t.draggerTopLeft);
    t.draggerTopLeft = undefined;
  }
  if (t.draggerTop !== undefined) {
    t.draggerTop.parentElement.removeChild(t.draggerTop);
    t.draggerTop = undefined;
  }
  if (t.draggerTopRight !== undefined) {
    t.draggerTopRight.parentElement.removeChild(t.draggerTopRight);
    t.draggerTopRight = undefined;
  }
  if (t.draggerLeft !== undefined) {
    t.draggerLeft.parentElement.removeChild(t.draggerLeft);
    t.draggerLeft = undefined;
  }
  if (t.draggerRight !== undefined) {
    t.draggerRight.parentElement.removeChild(t.draggerRight);
    t.draggerRight = undefined;
  }
  if (t.draggerBottomLeft !== undefined) {
    t.draggerBottomLeft.parentElement.removeChild(t.draggerBottomLeft);
    t.draggerBottomLeft = undefined;
  }
  if (t.draggerBottom !== undefined) {
    t.draggerBottom.parentElement.removeChild(t.draggerBottom);
    t.draggerBottom = undefined;
  }
  if (t.draggerBottomRight !== undefined) {
    t.draggerBottomRight.parentElement.removeChild(t.draggerBottomRight);
    t.draggerBottomRight = undefined;
  }
}
function addBodyElement(e, t, o) {
  var n = document.createElement(t);
  n.classList = o;
  n.style.zIndex = "99999999";
  e.designerContainer.appendChild(n);
  return n;
}
function showSelectedControlDragPoints(e, t) {
  var o = { left: true, top: true, right: true, bottom: true, corners: true };
  if (t.properties.Dock === e.tbDockLeft) {
    o = { left: false, top: false, right: true, bottom: false, corners: false };
  } else if (t.properties.Dock === e.tbDockRight) {
    o = { left: true, top: false, right: false, bottom: false, corners: false };
  } else if (t.properties.Dock === e.tbDockTop) {
    o = { left: false, top: false, right: false, bottom: true, corners: false };
  } else if (t.properties.Dock === e.tbDockBottom) {
    o = { left: false, top: true, right: false, bottom: false, corners: false };
  } else if (t.properties.Dock === e.tbDockFill) {
    o = {
      left: false,
      top: false,
      right: false,
      bottom: false,
      corners: false,
    };
  }
  var n = { x: 0, y: 0 };
  if (t === e.designer) return;
  var i = t.parentElement;
  while (i !== e.designerContainer && i !== null) {
    n.x += i.offsetLeft;
    n.y += i.offsetTop;
    i = i.parentElement;
  }
  if (!isRectangularControl(e, t)) {
    if (t.draggerLeft === undefined) {
      t.draggerLeft = addBodyElement(
        e,
        "div",
        "selectedControlDragPointLeft crosshair"
      );
      t.draggerLeft.ownerControl = t;
      t.draggerLeft.onmousedown = (t) => draggerLeft_onmousedown_line(e, t);
    }
    t.draggerLeft.style.left =
      n.x + (t.properties.X1 - dragPointWidth2 / 2) + "px";
    t.draggerLeft.style.top =
      n.y + (t.properties.Y1 - dragPointHeight2 / 2) + "px";
    t.draggerLeft.style.visibility = "visible";
    if (t.draggerRight === undefined) {
      t.draggerRight = addBodyElement(
        e,
        "div",
        "selectedControlDragPointRight crosshair"
      );
      t.draggerRight.ownerControl = t;
      t.draggerRight.onmousedown = (t) => draggerRight_onmousedown_line(e, t);
    }
    t.draggerRight.style.left =
      n.x + (t.properties.X2 - dragPointWidth2 / 2) + "px";
    t.draggerRight.style.top =
      n.y + (t.properties.Y2 - dragPointHeight2 / 2) + "px";
    t.draggerRight.style.visibility = "visible";
    return;
  }
  var r = isControlLocked(e, t.properties.Name);
  t.classList.remove("hasLockedIcon");
  if (r) {
    t.classList.add("hasLockedIcon");
  }
  {
    if (t.draggerTopLeft === undefined) {
      t.draggerTopLeft = addBodyElement(
        e,
        "div",
        "selectedControlDragPointTopLeft"
      );
      t.draggerTopLeft.ownerControl = t;
      t.draggerTopRight = addBodyElement(
        e,
        "div",
        "selectedControlDragPointTopRight"
      );
      t.draggerTopRight.ownerControl = t;
      t.draggerBottomLeft = addBodyElement(
        e,
        "div",
        "selectedControlDragPointBottomLeft"
      );
      t.draggerBottomLeft.ownerControl = t;
      t.draggerBottomRight = addBodyElement(
        e,
        "div",
        "selectedControlDragPointBottomRight"
      );
      t.draggerBottomRight.ownerControl = t;
    }
    if (!o.corners) {
      t.draggerTopLeft.classList.add("selectedControlDragPointInactive");
      t.draggerTopRight.classList.add("selectedControlDragPointInactive");
      t.draggerBottomLeft.classList.add("selectedControlDragPointInactive");
      t.draggerBottomRight.classList.add("selectedControlDragPointInactive");
      t.draggerTopLeft.onmousedown = undefined;
      t.draggerTopRight.onmousedown = undefined;
      t.draggerBottomLeft.onmousedown = undefined;
      t.draggerBottomRight.onmousedown = undefined;
    } else {
      t.draggerTopLeft.classList.remove("selectedControlDragPointInactive");
      t.draggerTopRight.classList.remove("selectedControlDragPointInactive");
      t.draggerBottomLeft.classList.remove("selectedControlDragPointInactive");
      t.draggerBottomRight.classList.remove("selectedControlDragPointInactive");
      t.draggerTopLeft.onmousedown = (t) => draggerTopLeft_onmousedown(e, t);
      t.draggerTopRight.onmousedown = (t) => draggerTopRight_onmousedown(e, t);
      t.draggerBottomLeft.onmousedown = (t) =>
        draggerBottomLeft_onmousedown(e, t);
      t.draggerBottomRight.onmousedown = (t) =>
        draggerBottomRight_onmousedown(e, t);
    }
    t.draggerTopLeft.style.left =
      n.x + (t.properties.Left - dragPointWidth2) + "px";
    t.draggerTopLeft.style.top =
      n.y + (t.properties.Top - dragPointHeight2) + "px";
    t.draggerTopLeft.style.visibility = "visible";
    t.draggerTopRight.style.left =
      n.x + (t.properties.Left + parseInt(t.offsetWidth)) + "px";
    t.draggerTopRight.style.top =
      n.y + (t.properties.Top - dragPointHeight2) + "px";
    t.draggerTopRight.style.visibility = "visible";
    t.draggerBottomLeft.style.left =
      n.x + (t.properties.Left - dragPointWidth2) + "px";
    t.draggerBottomLeft.style.top =
      n.y + (t.properties.Top + parseInt(t.offsetHeight)) + "px";
    t.draggerBottomLeft.style.visibility = "visible";
    t.draggerBottomRight.style.left =
      n.x + (t.properties.Left + parseInt(t.offsetWidth)) + "px";
    t.draggerBottomRight.style.top =
      n.y + (t.properties.Top + parseInt(t.offsetHeight)) + "px";
    t.draggerBottomRight.style.visibility = "visible";
  }
  if (o.left) {
    if (t.draggerLeft === undefined) {
      t.draggerLeft = addBodyElement(e, "div", "selectedControlDragPointLeft");
      t.draggerLeft.ownerControl = t;
      t.draggerLeft.onmousedown = (t) => draggerLeft_onmousedown(e, t);
    }
    t.draggerLeft.style.left =
      n.x + (t.properties.Left - dragPointWidth2) + "px";
    t.draggerLeft.style.top =
      n.y +
      (t.properties.Top + (parseInt(t.offsetHeight) - dragPointHeight2) / 2) +
      "px";
    t.draggerLeft.style.visibility = "visible";
  }
  if (o.top) {
    if (t.draggerTop === undefined) {
      t.draggerTop = addBodyElement(e, "div", "selectedControlDragPointTop");
      t.draggerTop.ownerControl = t;
      t.draggerTop.onmousedown = (t) => draggerTop_onmousedown(e, t);
    }
    t.draggerTop.style.left =
      n.x +
      (t.properties.Left + (parseInt(t.offsetWidth) - dragPointWidth2) / 2) +
      "px";
    t.draggerTop.style.top = n.y + (t.properties.Top - dragPointHeight2) + "px";
    t.draggerTop.style.visibility = "visible";
  }
  if (o.right) {
    if (t.draggerRight === undefined) {
      t.draggerRight = addBodyElement(
        e,
        "div",
        "selectedControlDragPointRight"
      );
      t.draggerRight.ownerControl = t;
      t.draggerRight.onmousedown = (t) => draggerRight_onmousedown(e, t);
    }
    t.draggerRight.style.left =
      n.x + (t.properties.Left + parseInt(t.offsetWidth)) + "px";
    t.draggerRight.style.top =
      n.y +
      (t.properties.Top + (parseInt(t.offsetHeight) - dragPointHeight2) / 2) +
      "px";
    t.draggerRight.style.visibility = "visible";
  }
  if (o.bottom) {
    if (t.draggerBottom === undefined) {
      t.draggerBottom = addBodyElement(
        e,
        "div",
        "selectedControlDragPointBottom"
      );
      t.draggerBottom.ownerControl = t;
      t.draggerBottom.onmousedown = (t) => draggerBottom_onmousedown(e, t);
    }
    t.draggerBottom.style.left =
      n.x +
      (t.properties.Left + (parseInt(t.offsetWidth) - dragPointWidth2) / 2) +
      "px";
    t.draggerBottom.style.top =
      n.y + (t.properties.Top + parseInt(t.offsetHeight)) + "px";
    t.draggerBottom.style.visibility = "visible";
  }
  if (!r && !t.hasFixedSize) {
    if (t.draggerTopLeft) t.draggerTopLeft.classList.remove("isLocked");
    if (t.draggerTop) t.draggerTop.classList.remove("isLocked");
    if (t.draggerTopRight) t.draggerTopRight.classList.remove("isLocked");
    if (t.draggerLeft) t.draggerLeft.classList.remove("isLocked");
    if (t.draggerRight) t.draggerRight.classList.remove("isLocked");
    if (t.draggerBottomLeft) t.draggerBottomLeft.classList.remove("isLocked");
    if (t.draggerBottom) t.draggerBottom.classList.remove("isLocked");
    if (t.draggerBottomRight) t.draggerBottomRight.classList.remove("isLocked");
  } else {
    if (t.draggerTopLeft) t.draggerTopLeft.classList.add("isLocked");
    if (t.draggerTop) t.draggerTop.classList.add("isLocked");
    if (t.draggerTopRight) t.draggerTopRight.classList.add("isLocked");
    if (t.draggerLeft) t.draggerLeft.classList.add("isLocked");
    if (t.draggerRight) t.draggerRight.classList.add("isLocked");
    if (t.draggerBottomLeft) t.draggerBottomLeft.classList.add("isLocked");
    if (t.draggerBottom) t.draggerBottom.classList.add("isLocked");
    if (t.draggerTopRight) t.draggerBottomRight.classList.add("isLocked");
  }
  syncFormDragPoints(e);
}
function syncUserScaledWidthHeight(e, t) {
  if (t.properties.ScaleMode === "vbUser") {
    if (t.properties.__cachedWidth && t.properties.__cachedScaledWidthFactor) {
      if (t.properties.__cachedWidth !== t.properties.Width) {
        t.properties.ScaleWidth =
          t.properties.Width * t.properties.__cachedScaledWidthFactor;
      }
    }
    if (
      t.properties.__cachedHeight &&
      t.properties.__cachedScaledHeightFactor
    ) {
      if (t.properties.__cachedHeight !== t.properties.Height) {
        t.properties.ScaleHeight =
          t.properties.Height * t.properties.__cachedScaledHeightFactor;
      }
    }
  }
}
function controlSnapToGrid(e, t) {
  var o = t.properties.Top % e.alignToGridY;
  if (o) {
    t.properties.Top -= o;
    t.properties.Height += o;
  }
  var n = t.properties.Height % e.alignToGridY;
  if (n) t.properties.Height -= n;
  var i = t.properties.Left % e.alignToGridX;
  if (i) {
    t.properties.Left -= i;
    t.properties.Width += i;
  }
  var r = t.properties.Width % e.alignToGridX;
  if (r) t.properties.Width -= r;
}
function controlSnapToGrid_line(e, t) {
  var o = t.properties.Y1 % e.alignToGridY;
  if (o) t.properties.Y1 -= o;
  var n = t.properties.Y2 % e.alignToGridY;
  if (n) t.properties.Y2 -= n;
  var i = t.properties.X1 % e.alignToGridX;
  if (i) t.properties.X1 -= i;
  var r = t.properties.X2 % e.alignToGridX;
  if (r) t.properties.X2 -= r;
}
function undoPointIfSelectedControlsPositionChanged(e, t, o, n) {
  e.isDragging = false;
  e.afterGotAllImages = () => {
    var i = 0;
    e.selectedControls.forEach((t) => {
      if (
        t.LastPositionX !== t.properties.Left ||
        t.LastPositionY !== t.properties.Top ||
        t.LastPositionWidth !== t.properties.Width ||
        t.LastPositionHeight !== t.properties.Height
      ) {
        i++;
        doAnchoringAdjustments(e, t, true);
      }
    });
    if (i > 0) {
      undoPoint(e);
      syncPropertySheet(e);
    } else {
      if (t && e.selectedControls.length === 1) {
        if (performance.now() - t < 1e3) {
          changeSelectedControlsProperty(e, "_designerClick", (n << 16) | o);
        }
      }
    }
  };
  var i = 0;
  e.selectedControls.forEach((t) => {
    if (t.controlNeedsReimaging) {
      t.controlNeedsReimaging = false;
      getImageFromServer(e, t);
      i += 1;
    }
  });
  if (i == 0) {
    if (e.afterGotAllImages) {
      let t = e.afterGotAllImages;
      e.afterGotAllImages = undefined;
      t();
    }
  }
}
function draggerBottomRight_onmousedown(e, t) {
  StoreSelectedControlsLastPositions(e);
  e.isDragging = true;
  e.rootElement.onmousemove = (o) => {
    var n = o.clientX - t.clientX;
    var i = o.clientY - t.clientY;
    n = Math.trunc(n / e.zoomRatio);
    i = Math.trunc(i / e.zoomRatio);
    e.selectedControls.forEach((t) => {
      if (isControlLocked(e, t.properties.Name)) return;
      t.properties.Width = t.LastPositionWidth + n;
      t.properties.Height = t.LastPositionHeight + i;
      if (e.alignToGrid) controlSnapToGrid(e, t);
      syncUserScaledWidthHeight(e, t);
      getImageFromServer(e, t);
      syncDesignerControlToProperties(e, t);
      showSelectedControlDragPoints(e, t);
      doAnchoringAdjustments(e, t, false);
    });
    syncPropertySheet(e);
  };
  e.rootElement.onmouseup2 = () =>
    undoPointIfSelectedControlsPositionChanged(e);
}
function draggerRight_onmousedown(e, t) {
  StoreSelectedControlsLastPositions(e);
  e.isDragging = true;
  e.rootElement.onmousemove = (o) => {
    var n = o.clientX - t.clientX;
    n = Math.trunc(n / e.zoomRatio);
    e.selectedControls.forEach((t) => {
      if (isControlLocked(e, t.properties.Name)) return;
      t.properties.Width = t.LastPositionWidth + n;
      if (e.alignToGrid) controlSnapToGrid(e, t);
      syncUserScaledWidthHeight(e, t);
      getImageFromServer(e, t);
      syncDesignerControlToProperties(e, t);
      showSelectedControlDragPoints(e, t);
      doAnchoringAdjustments(e, t, false);
      if (t.properties.Dock !== undefined && t.properties.Dock !== e.tbDockNone)
        doAnchoringAdjustments(t.parentElement, false);
    });
    syncPropertySheet(e);
  };
  e.rootElement.onmouseup2 = () =>
    undoPointIfSelectedControlsPositionChanged(e);
}
function draggerBottom_onmousedown(e, t) {
  StoreSelectedControlsLastPositions(e);
  e.isDragging = true;
  e.rootElement.onmousemove = (o) => {
    var n = o.clientY - t.clientY;
    n = Math.trunc(n / e.zoomRatio);
    e.selectedControls.forEach((t) => {
      if (isControlLocked(e, t.properties.Name)) return;
      t.properties.Height = t.LastPositionHeight + n;
      if (e.alignToGrid) controlSnapToGrid(e, t);
      getImageFromServer(e, t);
      syncDesignerControlToProperties(e, t);
      showSelectedControlDragPoints(e, t);
      doAnchoringAdjustments(e, t, false);
      if (t.properties.Dock !== undefined && t.properties.Dock !== e.tbDockNone)
        doAnchoringAdjustments(t.parentElement, false);
    });
    syncPropertySheet(e);
  };
  e.rootElement.onmouseup2 = () =>
    undoPointIfSelectedControlsPositionChanged(e);
}
function draggerTop_onmousedown(e, t) {
  StoreSelectedControlsLastPositions(e);
  e.isDragging = true;
  e.rootElement.onmousemove = (o) => {
    var n = o.clientY - t.clientY;
    n = Math.trunc(n / e.zoomRatio);
    e.selectedControls.forEach((t) => {
      if (isControlLocked(e, t.properties.Name)) return;
      t.properties.Top = t.LastPositionY + n;
      t.properties.Height = t.LastPositionHeight - n;
      if (e.alignToGrid) controlSnapToGrid(e, t);
      getImageFromServer(e, t);
      syncDesignerControlToProperties(e, t);
      showSelectedControlDragPoints(e, t);
      doAnchoringAdjustments(e, t, false);
      if (t.properties.Dock !== undefined && t.properties.Dock !== e.tbDockNone)
        doAnchoringAdjustments(t.parentElement, false);
    });
    syncPropertySheet(e);
  };
  e.rootElement.onmouseup2 = () =>
    undoPointIfSelectedControlsPositionChanged(e);
}
function draggerTopLeft_onmousedown(e, t) {
  StoreSelectedControlsLastPositions(e);
  e.isDragging = true;
  e.rootElement.onmousemove = (o) => {
    var n = o.clientY - t.clientY;
    var i = o.clientX - t.clientX;
    i = Math.trunc(i / e.zoomRatio);
    n = Math.trunc(n / e.zoomRatio);
    e.selectedControls.forEach((t) => {
      if (isControlLocked(e, t.properties.Name)) return;
      t.properties.Top = t.LastPositionY + n;
      t.properties.Height = t.LastPositionHeight - n;
      t.properties.Left = t.LastPositionX + i;
      t.properties.Width = t.LastPositionWidth - i;
      if (e.alignToGrid) controlSnapToGrid(e, t);
      syncUserScaledWidthHeight(e, t);
      getImageFromServer(e, t);
      syncDesignerControlToProperties(e, t);
      showSelectedControlDragPoints(e, t);
      doAnchoringAdjustments(e, t, false);
    });
    syncPropertySheet(e);
  };
  e.rootElement.onmouseup2 = () =>
    undoPointIfSelectedControlsPositionChanged(e);
}
function draggerLeft_onmousedown(e, t) {
  StoreSelectedControlsLastPositions(e);
  e.isDragging = true;
  e.rootElement.onmousemove = (o) => {
    var n = o.clientX - t.clientX;
    n = Math.trunc(n / e.zoomRatio);
    e.selectedControls.forEach((t) => {
      if (isControlLocked(e, t.properties.Name)) return;
      t.properties.Left = t.LastPositionX + n;
      t.properties.Width = t.LastPositionWidth - n;
      if (e.alignToGrid) controlSnapToGrid(e, t);
      syncUserScaledWidthHeight(e, t);
      getImageFromServer(e, t);
      syncDesignerControlToProperties(e, t);
      showSelectedControlDragPoints(e, t);
      doAnchoringAdjustments(e, t, false);
      if (t.properties.Dock !== undefined && t.properties.Dock !== e.tbDockNone)
        doAnchoringAdjustments(t.parentElement, false);
    });
    syncPropertySheet(e);
  };
  e.rootElement.onmouseup2 = () =>
    undoPointIfSelectedControlsPositionChanged(e);
}
function draggerBottomLeft_onmousedown(e, t) {
  StoreSelectedControlsLastPositions(e);
  e.isDragging = true;
  e.rootElement.onmousemove = (o) => {
    var n = o.clientY - t.clientY;
    var i = o.clientX - t.clientX;
    i = Math.trunc(i / e.zoomRatio);
    n = Math.trunc(n / e.zoomRatio);
    e.selectedControls.forEach((t) => {
      if (isControlLocked(e, t.properties.Name)) return;
      t.properties.Height = t.LastPositionHeight + n;
      t.properties.Left = t.LastPositionX + i;
      t.properties.Width = t.LastPositionWidth - i;
      if (e.alignToGrid) controlSnapToGrid(e, t);
      syncUserScaledWidthHeight(e, t);
      getImageFromServer(e, t);
      syncDesignerControlToProperties(e, t);
      showSelectedControlDragPoints(e, t);
      doAnchoringAdjustments(e, t, false);
    });
    syncPropertySheet(e);
  };
  e.rootElement.onmouseup2 = () =>
    undoPointIfSelectedControlsPositionChanged(e);
}
function draggerTopRight_onmousedown(e, t) {
  StoreSelectedControlsLastPositions(e);
  e.isDragging = true;
  e.rootElement.onmousemove = (o) => {
    var n = o.clientY - t.clientY;
    var i = o.clientX - t.clientX;
    i = Math.trunc(i / e.zoomRatio);
    n = Math.trunc(n / e.zoomRatio);
    e.selectedControls.forEach((t) => {
      if (isControlLocked(e, t.properties.Name)) return;
      t.properties.Top = t.LastPositionY + n;
      t.properties.Height = t.LastPositionHeight - n;
      t.properties.Width = t.LastPositionWidth + i;
      if (e.alignToGrid) controlSnapToGrid(e, t);
      syncUserScaledWidthHeight(e, t);
      getImageFromServer(e, t);
      syncDesignerControlToProperties(e, t);
      showSelectedControlDragPoints(e, t);
      doAnchoringAdjustments(e, t, false);
    });
    syncPropertySheet(e);
  };
  e.rootElement.onmouseup2 = () =>
    undoPointIfSelectedControlsPositionChanged(e);
}
function draggerLeft_onmousedown_line(e, t) {
  StoreSelectedControlsLastPositions(e);
  e.isDragging = true;
  e.rootElement.onmousemove = (o) => {
    var n = o.clientX - t.clientX;
    n = Math.trunc(n / e.zoomRatio);
    var i = o.clientY - t.clientY;
    i = Math.trunc(i / e.zoomRatio);
    e.selectedControls.forEach((t) => {
      if (isControlLocked(e, t.properties.Name)) return;
      t.properties.X1 = t.LastPositionX1 + n;
      t.properties.Y1 = t.LastPositionY1 + i;
      if (e.alignToGrid) controlSnapToGrid_line(e, t);
      let o = t.parentNode;
      let r = 0;
      let s = 0;
      while (o && o != e.designerContainer) {
        r += o.offsetLeft;
        s += o.offsetTop;
        o = o.parentNode;
      }
      drawDiagonalLine(
        r + t.properties.X1,
        s + t.properties.Y1,
        r + t.properties.X2,
        s + t.properties.Y2
      );
      getImageFromServer(e, t);
      syncDesignerControlToProperties(e, t);
      showSelectedControlDragPoints(e, t);
      doAnchoringAdjustments(e, t, false);
      if (t.properties.Dock !== undefined && t.properties.Dock !== e.tbDockNone)
        doAnchoringAdjustments(t.parentElement, false);
    });
    syncPropertySheet(e);
  };
  e.rootElement.onmouseup2 = () =>
    undoPointIfSelectedControlsPositionChanged(e);
}
function draggerRight_onmousedown_line(e, t) {
  StoreSelectedControlsLastPositions(e);
  e.isDragging = true;
  e.rootElement.onmousemove = (o) => {
    var n = o.clientX - t.clientX;
    n = Math.trunc(n / e.zoomRatio);
    var i = o.clientY - t.clientY;
    i = Math.trunc(i / e.zoomRatio);
    e.selectedControls.forEach((t) => {
      if (isControlLocked(e, t.properties.Name)) return;
      t.properties.X2 = t.LastPositionX2 + n;
      t.properties.Y2 = t.LastPositionY2 + i;
      if (e.alignToGrid) controlSnapToGrid_line(e, t);
      let o = t.parentNode;
      let r = 0;
      let s = 0;
      while (o && o != e.designerContainer) {
        r += o.offsetLeft;
        s += o.offsetTop;
        o = o.parentNode;
      }
      drawDiagonalLine(
        r + t.properties.X1,
        s + t.properties.Y1,
        r + t.properties.X2,
        s + t.properties.Y2
      );
      getImageFromServer(e, t);
      syncDesignerControlToProperties(e, t);
      showSelectedControlDragPoints(e, t);
      doAnchoringAdjustments(e, t, false);
      if (t.properties.Dock !== undefined && t.properties.Dock !== e.tbDockNone)
        doAnchoringAdjustments(t.parentElement, false);
    });
    syncPropertySheet(e);
  };
  e.rootElement.onmouseup2 = () =>
    undoPointIfSelectedControlsPositionChanged(e);
}
function unselectControl(e, t) {
  removeSelectedControlDragPoints(e, t);
  e.selectedControls = e.selectedControls.filter((e) => e !== t);
  changedSelectedControls(e);
  t.classList.remove("baseControlSelected");
  t.isSelected = false;
  e.allMenubarItems.forEach((t) => {
    t.changedSelection(e);
  });
  changedSelection(e);
}
function changedSelectedControls(e) {
  e.restorePropertiesBoxScroll = undefined;
  if (
    !e.dontHidePopupMenus &&
    (e.selectedControls.length === 0 ||
      e.selectedControls[0].properties._className !== "Menu")
  ) {
    hideAllPopupMenuDesigners(e);
  }
}
function unselectAllControlsPre(e) {
  e.selectedControls.forEach((t) => {
    removeSelectedControlDragPoints(e, t);
    t.classList.remove("baseControlSelected");
    t.isSelected = false;
    if (t.menuControl) {
      t.menuControl.classList.remove("selectedMenuItem");
    }
  });
}
function unselectAllControls(e, t) {
  unselectAllControlsPre(e);
  e.selectedControls = [];
  changedSelectedControls(e);
  e.allMenubarItems.forEach((t) => {
    t.changedSelection(e);
  });
  if (!e.dontUpdatePropertySheet) e.propertySheet.innerHTML = "";
  if (t !== true) e.formSelectorOption.selected = true;
  e.selectedControls = [e.designer];
  changedSelectedControls(e);
  e.designer.isSelected = true;
}
function startSelectionArea(e, t, o) {
  t /= e.zoomRatio;
  o /= e.zoomRatio;
  if (e.alignToGrid) {
    var n = t % e.alignToGridX;
    if (n) t -= n;
    var i = o % e.alignToGridY;
    if (i) o -= i;
  }
  var r = false;
  if (e.selectedTool.controlType === "Line") {
    drawDiagonalLine(t, o, t, o);
    r = true;
    e.selectionArea.classList.add("selectionAreaLineControl");
  } else {
    e.selectionArea.classList.remove("selectionAreaLineControl");
  }
  e.selectionArea.style.visibility = "visible";
  e.selectionArea.style.left = t + "px";
  e.selectionArea.style.top = o + "px";
  e.selectionArea.style.width = "0px";
  e.selectionArea.style.height = "0px";
  e.selectionArea.style.cursor = e.designerContainer.style.cursor;
  e.selectionArea.XXX_startX = t;
  e.selectionArea.XXX_startY = o;
  e.designer.classList.add("noControlPointerEvents");
  if (e.selectedTool === e.toolBoxPointer) {
    e.selectionArea.classList.remove("selectionAreaNewControl");
  } else {
    e.selectionArea.classList.add("selectionAreaNewControl");
  }
  e.designerContainer.onmousemove = (n) => {
    var i = n.offsetX / e.zoomRatio;
    var s = n.offsetY / e.zoomRatio;
    i -= e.alignToGrid ? i % e.alignToGridX : 0;
    s -= e.alignToGrid ? s % e.alignToGridY : 0;
    var a = 0;
    var l = 0;
    var d = n.target;
    while (d !== e.designerContainer && d !== null) {
      a += d.offsetLeft;
      l += d.offsetTop;
      d = d.parentElement;
    }
    e.selectionArea.XXX_targetID = n.target.id;
    e.selectionArea.XXX_offsetX = a + n.offsetX;
    e.selectionArea.XXX_OffsetY = l + n.offsetY;
    var c = a + i - t;
    var u = l + s - o;
    if (r) drawDiagonalLine(t, o, a + i, l + s);
    if (c < 0) {
      e.selectionArea.style.left = t + c + "px";
      e.selectionArea.style.width = -c + "px";
    } else {
      e.selectionArea.style.left = t + "px";
      e.selectionArea.style.width = c + "px";
    }
    if (u < 0) {
      e.selectionArea.style.top = o + u + "px";
      e.selectionArea.style.height = -u + "px";
    } else {
      e.selectionArea.style.top = o + "px";
      e.selectionArea.style.height = u + "px";
    }
    if (e.selectedTool !== e.toolBoxPointer && !r) {
      setSelectionDragInfo(e, e.selectionArea, false);
    }
  };
}
function trunc2dp(e) {
  return Math.trunc(e * 100) / 100;
}
function setSelectionDragInfo(e, t, o) {
  var n = 0;
  var i = 0;
  if (o) {
    var r = { x: 0, y: 0 };
    var s = t.parentElement;
    while (s !== e.designer && s !== null) {
      r.x += s.offsetLeft;
      r.y += s.offsetTop;
      s = s.parentElement;
    }
    n = r.x;
    i = r.y;
  }
  if (isRectangularControl(e, t)) {
    e.selectionAreaDragInfoLeft.innerHTML =
      "x:" + t.offsetLeft + " y:" + t.offsetTop;
    e.selectionAreaDragInfoLeft.style.top =
      i + t.offsetTop + (t.clientHeight + 4) + "px";
    e.selectionAreaDragInfoLeft.style.left = n + t.offsetLeft + 15 + "px";
    e.selectionAreaDragInfoLeft.style.visibility = "visible";
    e.selectionAreaDragInfoRight.innerHTML =
      t.offsetWidth + " x " + t.offsetHeight;
    e.selectionAreaDragInfoRight.style.top =
      i + t.offsetTop + (t.clientHeight + 4) + "px";
    e.selectionAreaDragInfoRight.style.left =
      n +
      t.offsetLeft +
      (t.clientWidth - e.selectionAreaDragInfoRight.clientWidth - 15) +
      "px";
    e.selectionAreaDragInfoRight.style.visibility = "visible";
  } else {
    e.selectionAreaDragInfoLeft.innerHTML =
      "(" +
      trunc2dp(t.properties.X1) +
      "," +
      trunc2dp(t.properties.Y1) +
      ")-(" +
      trunc2dp(t.properties.X2) +
      "," +
      trunc2dp(t.properties.Y2) +
      ")";
    e.selectionAreaDragInfoLeft.style.top =
      i + t.offsetTop + (t.clientHeight + 4) + "px";
    e.selectionAreaDragInfoLeft.style.left = n + t.offsetLeft + 15 + "px";
    e.selectionAreaDragInfoLeft.style.visibility = "visible";
  }
  if (
    e.selectionAreaDragInfoLeft.offsetLeft +
      e.selectionAreaDragInfoLeft.offsetWidth >
    e.selectionAreaDragInfoRight.offsetLeft
  ) {
    e.selectionAreaDragInfoRight.style.top =
      parseInt(e.selectionAreaDragInfoRight.style.top) +
      e.selectionAreaDragInfoLeft.offsetHeight +
      "px";
  }
  if (
    e.selectionAreaDragInfoRight.offsetLeft <
    e.selectionAreaDragInfoLeft.offsetLeft
  ) {
    e.selectionAreaDragInfoRight.style.left =
      e.selectionAreaDragInfoLeft.style.left;
  }
}
function resyncParentIndexes(e) {
  e.allControls.forEach((e) => {
    var t = e.parentNode;
    e.parentIndex = Array.prototype.indexOf.call(t.children, e);
    if (e.properties._paintedByParent) {
      e.style.zIndex = e.parentIndex;
    } else {
      e.style.zIndex = e.parentIndex + WINDOWED_CONTROLS_ZINDEX_OFFSET;
    }
  });
}
function bringToFront(e) {
  e.selectedControls.forEach((t) => {
    var o = t.parentElement;
    o.removeChild(t);
    o.appendChild(t);
    if (t.properties._paintedByParent) addPendingControl(e, t);
  });
  resyncParentIndexes(e);
  refreshPendingControls(e);
  undoPoint(e);
}
function sendToBack(e) {
  e.selectedControls.forEach((t) => {
    var o = t.parentElement;
    o.removeChild(t);
    o.insertBefore(t, o.firstChild);
    if (t.properties._paintedByParent) addPendingControl(e, t);
  });
  resyncParentIndexes(e);
  refreshPendingControls(e);
  undoPoint(e);
}
function lockControls(e) {
  e.selectedControls.forEach((t) => {
    lockTheControl(e, t.properties.Name);
  });
}
function unlockControls(e) {
  e.selectedControls.forEach((t) => {
    unlockTheControl(e, t.properties.Name);
  });
}
function lockAllControls(e) {
  e.allControls.forEach((t) => {
    lockTheControl(e, t.properties.Name);
  });
  e.selectedControls = e.allControls.filter(() => true);
  changedSelectedControls(e);
  StoreSelectedControlsLastPositions(e);
}
function unlockAllControls(e) {
  e.allControls.forEach((t) => {
    unlockTheControl(e, t.properties.Name);
  });
  e.selectedControls = e.allControls.filter(() => true);
  changedSelectedControls(e);
  StoreSelectedControlsLastPositions(e);
}
function alignToGridNow(e) {
  e.selectedControls.forEach((t) => {
    var o = isControlLocked(e, t.properties.Name);
    if (!o) {
      controlSnapToGrid(e, t);
      getImageFromServer(e, t);
      syncDesignerControlToProperties(e, t);
      showSelectedControlDragPoints(e, t);
      doAnchoringAdjustments(e, t, false);
    }
  });
}
function showDesignerContextMenu(e, t, o, n, i) {
  if (e.rootElement.onclick && t === e.contextMenu) e.rootElement.onclick(o);
  e.rootElement.onclick = (t) => {
    if (t.target.classList.contains("contextMenuItem")) return;
    e.contextMenu.style.visibility = "hidden";
    if (i) i(e);
    e.contextMenu2.style.visibility = "hidden";
    e.contextMenuUnderlay.classList.remove("contextMenuUnderlayON");
    if (e.contextMenuRevealTimer) {
      clearTimeout(e.contextMenuRevealTimer);
      e.contextMenuRevealTimer = undefined;
    }
    e.rootElement.onclick = undefined;
  };
  e.contextMenuUnderlay.classList.add("contextMenuUnderlayON");
  t.style.left = o.clientX - e.rootElement.offsetLeft + "px";
  t.style.top = o.clientY - e.rootElement.offsetTop + "px";
  t.innerHTML = "";
  t.onblur = () => {
    t.style.visibility = "hidden";
    if (i) i(e);
    if (e.contextMenuRevealTimer) {
      clearTimeout(e.contextMenuRevealTimer);
      e.contextMenuRevealTimer = undefined;
    }
  };
  t.tabindex = -1;
  t.focus();
  var r = undefined;
  n.forEach((o) => {
    if (!o.isHidden) {
      if (o.name) {
        r = document.createElement("div");
        r.className = "contextMenuItem";
        r.innerHTML = o.name;
        r.onclick = (n) => {
          if (o.onclick) {
            t.style.visibility = "hidden";
            if (i) i(e);
            e.contextMenuUnderlay.classList.remove("contextMenuUnderlayON");
            o.onclick(n);
          }
        };
        r.onmouseenter = (n) => {
          if (t === e.contextMenu) e.contextMenu2.style.visibility = "hidden";
          if (e.contextMenuRevealTimer) {
            clearTimeout(e.contextMenuRevealTimer);
            e.contextMenuRevealTimer = undefined;
          }
          if (o.onreveal) {
            e.contextMenuRevealTimer = setTimeout(() => {
              t.onblur = undefined;
              o.onreveal(n);
            }, 500);
          }
        };
        r.onmouseout = (t) => {
          if (e.contextMenuRevealTimer) {
            clearTimeout(e.contextMenuRevealTimer);
            e.contextMenuRevealTimer = undefined;
          }
        };
      } else {
        r = document.createElement("div");
        r.className = "contextMenuItemSeperator";
      }
      t.appendChild(r);
    }
  });
  if (r !== undefined) {
    r.classList.add("contextMenuItemLast");
    t.style.visibility = "visible";
    if (t === e.contextMenu2) {
      t.style.left = e.contextMenu.offsetLeft - t.offsetWidth + "px";
    }
    var s = e.rootElement.getBoundingClientRect();
    if (t.offsetLeft + t.offsetWidth > s.right) {
      t.style.left = s.right - t.offsetWidth - 10 + "px";
    }
    t.style.maxHeight = s.right - t.offsetTop - 10 + "px";
    t.scrollTop = 0;
    t.scrollLeft = 0;
  }
}
function cancelContextMenu(e, t) {
  e.IgnoringEscapeKey = true;
}
function duplicateSelectedControls(e, t) {
  var o = JSON.stringify(serializeControls(e, e.selectedControls));
  var n = preparePaste(e);
  var i = deserializeControls(e, o, n.parentContainer, false, t);
  doPaste(e, n, i, true);
}
function document_onmousedown_rightClick(e, t) {
  cancelContextMenu(e, t);
  e.vscode.postMessage({ type: "getClipboardData", args: ["text/tbControls"] });
  e.gotClipboardDataFunction = (o) => {
    var n;
    try {
      n = JSON.parse(o);
    } catch (e) {}
    var i = true;
    if (!Array.isArray(n)) {
      i = false;
    }
    var r = false;
    var s = false;
    var a = false;
    var l;
    if (
      e.selectedControls.length === 1 &&
      e.selectedControls[0] === e.designer
    ) {
      var d = 0;
      e.allControls.forEach((t) => {
        if (isControlLocked(e, t.properties.Name)) {
          d++;
        }
      });
      l = [
        {
          name: "查看代码",
          onclick: () => {
            e.vscode.postMessage({ type: "viewCode" });
          },
        },
        {
          name: "粘贴",
          onclick: () => {
            e.vscode.postMessage({ type: "paste" });
          },
        },
        {
          name: "粘贴(同名, 控制数组)",
          onclick: () => {
            e.vscode.postMessage({ type: "paste2" });
          },
        },
        {
          name: "全选",
          onclick: () => {
            e.selectedControls = e.allControls.filter(() => true);
            changedSelectedControls(e);
            StoreSelectedControlsLastPositions(e);
          },
        },
      ];
      l[1].isHidden = !i;
      l[2].isHidden = !i || e.designer.properties._clsid === formCLSID_Custom;
      if (e.selectedControls.length > 0 && d != e.allControls.length) {
        l.push({
          name: "锁定所有控件",
          onclick: () => lockAllControls(e),
        });
      }
      if (d) {
        l.push({
          name: "解锁所有控件",
          onclick: () => unlockAllControls(e),
        });
      }
    } else {
      e.selectedControls.forEach((t) => {
        if (isControlLocked(e, t.properties.Name)) {
          s = true;
        } else {
          r = true;
        }
        if (t.properties["(Custom)"] !== undefined) {
          a = true;
        }
      });
      l = [
        {
          name: "剪切",
          onclick: () => {
            e.vscode.postMessage({ type: "cut" });
          },
        },
        {
          name: "复制",
          onclick: () => {
            e.vscode.postMessage({ type: "copy" });
          },
        },
        {
          name: "粘贴",
          onclick: () => {
            e.vscode.postMessage({ type: "paste" });
          },
        },
        {
          name: "粘贴(同名, 控制数组)",
          onclick: () => {
            e.vscode.postMessage({ type: "paste2" });
          },
        },
        {
          name: "复制(新名)",
          onclick: () => duplicateSelectedControls(e, false),
        },
        {
          name: "复制(同名, 控制数组)",
          onclick: () => duplicateSelectedControls(e, true),
        },
        { name: "置于最前", onclick: () => bringToFront(e) },
        { name: "置于最后", onclick: () => sendToBack(e) },
        { name: "对齐到网格", onclick: () => alignToGridNow(e) },
      ];
      if (r) {
        l.push({ name: "锁定控件", onclick: () => lockControls(e) });
      }
      if (s) {
        l.push({ name: "解锁控件", onclick: () => unlockControls(e) });
      }
      if (a) {
        l.push({
          name: "ActiveX 属性...",
          onclick: () => {
            changeSelectedControlsProperty(e, "_openPropertyPage", "Custom");
          },
        });
      }
      l[2].isHidden = !i;
      l[3].isHidden = !i || e.designer.properties._clsid === formCLSID_Custom;
      l[5].isHidden = e.designer.properties._clsid === formCLSID_Custom;
    }
    showDesignerContextMenu(e, e.contextMenu, t, l);
  };
}
function stopFlashing(e) {
  if (e.currentFlashingContainer !== undefined) {
    e.currentFlashingContainer.classList.remove("boxShadowRed");
    e.currentFlashingContainer = undefined;
  }
}
function document_onmousemove(e, t) {
  e.lastKnownMousePositionX = t.clientX;
  e.lastKnownMousePositionY = t.clientY;
  syncFormDragInfo(e);
  if (e.selectedTool === e.toolBoxPointer) {
    stopFlashing(e);
    if (e.isDragging || t.target.draggerTopLeft !== undefined) {
      e.designerContainer.style.cursor = "move";
    } else {
      e.designerContainer.style.cursor = "default";
    }
    var o = e.designer.getBoundingClientRect();
    o = { left: o.left * e.zoomRatio, top: o.top * e.zoomRatio };
    let n = (parseInt(t.clientX) - parseInt(o.left)) / e.zoomRatio;
    let i = (parseInt(t.clientY) - parseInt(o.top)) / e.zoomRatio;
    e.allControls.forEach((t) => {
      if (t.properties._className === "Line") {
        let r = t.properties.Y2 - t.properties.Y1;
        if (Math.abs(r) < 1) r = 1;
        let s = t.properties.X2 - t.properties.X1;
        if (Math.abs(s) < 1) s = 1;
        let a = 0;
        let l = 0;
        let d = t.parentNode;
        while (d && d != e.designerContainer) {
          a += d.properties.Left;
          l += d.properties.Top;
          d = d.parentNode;
        }
        let c = t.properties.X1 + a;
        let u = t.properties.Y1 + l;
        let p = t.properties.X2 + a;
        let f = t.properties.Y2 + l;
        var o = true;
        if (n >= c) {
          if (n > p) o = false;
        } else {
          if (n < p) o = false;
        }
        if (i >= u) {
          if (i > f) o = false;
        } else {
          if (i < f) o = false;
        }
        if (o) {
          let o = (n - c) / s;
          let d = (i - u) / r;
          let p = Math.abs((d - o) * r * s);
          if (p < 1e3) {
            let o = (7 + t.properties.BorderWidth / 4) / e.zoomRatio;
            t.classList.add("opacity0");
            t.style.left = n - o - a + "px";
            t.style.top = i - o - l + "px";
            t.style.width = o * 2 + "px";
            t.style.height = o * 2 + "px";
            t.style.border = "0";
            t.style.onmousedown = undefined;
            t.style.onmousemove = undefined;
            t.style.onmouseup = undefined;
            t.style.cursor = "grab";
          }
        }
      }
    });
    return;
  }
  if (e.selectionArea.style.visibility !== "hidden") return;
  var n = t.target;
  if (t.ctrlKey) {
    n = e.designerContainer;
  } else {
    while (
      n !== e.designerContainer &&
      n.properties._clsid !== "{E6E927FA-F6E6-4E8E-9540-DA8696F38429}" &&
      !n.properties._isFrame
    ) {
      n = n.parentElement;
    }
  }
  if (n === e.designerContainer) n = e.designer;
  if (e.currentFlashingContainer === n) return;
  stopFlashing(e);
  e.currentFlashingContainer = n;
  n.classList.add("boxShadowRed");
}
function document_onmouseout(e, t) {
  e.designerDragInfoLeft.style.visibility = "hidden";
}
function onClickedOnControl(e, t, o, n) {
  if (e.selectedControls.find((e) => e === t) !== undefined) {
    if (o || n) {
      unselectControl(e, t);
    }
  } else if (o || n) {
    if (t !== e.designer) {
      unselectControl(e, e.designer);
      e.selectedControls.push(t);
      changedSelectedControls(e);
      t.classList.add("baseControlSelected");
      t.isSelected = true;
      if (t !== e.designer) e.designerContainer.style.cursor = "move";
    }
  } else {
    e.selectedControls.forEach((t) => {
      removeSelectedControlDragPoints(e, t);
      t.classList.remove("baseControlSelected");
      t.isSelected = false;
    });
    e.selectedControls = [t];
    changedSelectedControls(e);
    t.classList.add("baseControlSelected");
    t.isSelected = true;
    if (t !== e.designer) e.designerContainer.style.cursor = "move";
  }
}
function document_onmousedown(e, t) {
  console.log("document_onmousedown");
  e.contextMenu.style.visibility = "hidden";
  setTimeout(() => {
    e.lastEvent_clientX = undefined;
    e.lastEvent_clientY = undefined;
    console.log("document_onmousedown(1)");
    if (e.selectedTool === e.toolBoxPointer) {
      if (t.target === e.designer || t.target === e.designerContainerOUTER) {
        if (t.shiftKey || t.ctrlKey) {
          onClickedOnControl(e, e.designer, t.shiftKey, t.ctrlKey);
          syncFormDragPoints(e);
        } else {
          e.dontUpdatePropertySheet = true;
          unselectAllControls(e);
          e.dontUpdatePropertySheet = false;
          changedSelection(e);
          startSelectionArea(e, t.offsetX, t.offsetY);
          syncFormDragPoints(e);
        }
      } else if (t.target.classList.contains("baseControl")) {
        let n = 0;
        if (
          t.button === 0 &&
          t.target.classList.contains("baseControlSelected")
        )
          n = performance.now();
        var o;
        if (
          e.selectedControls.length === 1 &&
          e.selectedControls[0].properties._clsid === t.target.properties._clsid
        ) {
          o = e.propertiesBoxInner.scrollTop;
        }
        onClickedOnControl(e, t.target, t.shiftKey, t.ctrlKey);
        StoreSelectedControlsLastPositions(e);
        changedSelection(e);
        if (o) {
          e.propertiesBoxInner.scrollTop = o;
        }
        if (
          t.target.properties.Dock !== "undefined" &&
          t.target.properties.Dock !== e.tbDockNone &&
          t.target.properties.Dock !== undefined
        ) {
        } else {
          e.isDragging = true;
          e.rootElement.onmousemove = (n) => {
            if (
              n.clientX === e.lastEvent_clientX &&
              n.clientY === e.lastEvent_clientY
            ) {
              return;
            }
            e.lastEvent_clientX = n.clientX;
            e.lastEvent_clientY = n.clientY;
            if (n.buttons !== 1) {
              undoPointIfSelectedControlsPositionChanged(e);
              return;
            }
            calculateInclusionCount(e, e.selectedControls);
            e.selectedControls.forEach((o) => {
              if (o.InclusionCount == 1) {
                if (isControlLocked(e, o.properties.Name)) return;
                if (isRectangularControl(e, o)) {
                  var i =
                    o.LastPositionX + (n.clientX - t.clientX) / e.zoomRatio;
                  var r =
                    o.LastPositionY + (n.clientY - t.clientY) / e.zoomRatio;
                  if (e.alignToGrid) {
                    var s = i % e.alignToGridX;
                    var a = r % e.alignToGridY;
                    if (s) i -= s;
                    if (a) r -= a;
                  }
                  o.properties.Left = i;
                  o.properties.Top = r;
                } else {
                  var l =
                    o.LastPositionX1 + (n.clientX - t.clientX) / e.zoomRatio;
                  var d =
                    o.LastPositionY1 + (n.clientY - t.clientY) / e.zoomRatio;
                  var c =
                    o.LastPositionX2 + (n.clientX - t.clientX) / e.zoomRatio;
                  var u =
                    o.LastPositionY2 + (n.clientY - t.clientY) / e.zoomRatio;
                  if (e.alignToGrid) {
                    var p = l % e.alignToGridX;
                    var f = d % e.alignToGridY;
                    if (p) l -= p;
                    if (f) d -= f;
                    if (p) c -= p;
                    if (f) u -= f;
                  }
                  o.properties.X1 = l;
                  o.properties.Y1 = d;
                  o.properties.X2 = c;
                  o.properties.Y2 = u;
                }
                syncDesignerControlToProperties(e, o);
                if (o.properties._paintedByParent) {
                  addPendingControl(e, o);
                }
              }
              showSelectedControlDragPoints(e, o);
            });
            refreshPendingControls(e);
            if (e.selectedControls.length == 1) {
              setSelectionDragInfo(e, e.selectedControls[0], true);
            }
            syncPropertySheet(e);
            if (o) {
              e.propertiesBoxInner.scrollTop = o;
            }
          };
          e.rootElement.onmouseup2 = () => {
            undoPointIfSelectedControlsPositionChanged(
              e,
              n,
              t.offsetX / e.zoomRatio,
              t.offsetY / e.zoomRatio
            );
            if (o) {
              e.propertiesBoxInner.scrollTop = o;
            }
          };
        }
        if (e.selectedControls.length == 1) {
          setSelectionDragInfo(e, e.selectedControls[0], true);
        }
      }
    } else {
      unselectAllControls(e);
      changedSelection(e);
      var n = 0;
      var i = 0;
      var r = t.target;
      while (r !== e.designerContainer && r !== null) {
        n += r.offsetLeft * e.zoomRatio;
        i += r.offsetTop * e.zoomRatio;
        r = r.parentElement;
      }
      startSelectionArea(e, n + t.offsetX, i + t.offsetY);
      syncFormDragPoints(e);
    }
    if (t.button == 2) {
      return document_onmousedown_rightClick(e, t);
    }
  }, 0);
}
function StoreSelectedControlsLastPositions(e) {
  e.selectedControls.forEach((t) => {
    if (
      t.properties._clsid !== formCLSID_Custom &&
      t.properties._clsid !== formCLSID_Windows &&
      t.properties._clsid !== formCLSID_WindowsUserControl &&
      t.properties._clsid !== formCLSID_WindowsPropertyPage
    ) {
      if (isRectangularControl(e, t)) {
        t.LastPositionX = t.properties.Left;
        t.LastPositionY = t.properties.Top;
        t.LastPositionWidth = t.properties.Width;
        t.LastPositionHeight = t.properties.Height;
      } else {
        t.LastPositionX1 = t.properties.X1;
        t.LastPositionY1 = t.properties.Y1;
        t.LastPositionX2 = t.properties.X2;
        t.LastPositionY2 = t.properties.Y2;
      }
      showSelectedControlDragPoints(e, t);
    }
    t.isSelected = true;
  });
  e.allMenubarItems.forEach((t) => {
    t.changedSelection(e);
  });
  syncPropertySheet(e);
}
function getArrayCommonPropertyValue(e, t, o) {
  var n = null;
  t.forEach((e) => {
    var t = e.properties[o];
    if (n === null || n === t) {
      n = t;
    } else {
      n = undefined;
    }
  });
  if (n === null) n = undefined;
  return n;
}
function setArrayCommonPropertyValue(e, t, o, n, i, r) {
  var s = 0;
  t.forEach((t) => {
    if (o == "Width" && !isRectangularControl(e, t)) {
      if (!isControlLocked(e, t.properties.Name)) {
        if (t.properties.X2 >= t.properties.X1) {
          t.properties.X2 = t.properties.X1 + n;
        } else {
          t.properties.X1 = t.properties.X2 + n;
        }
        syncDesignerControlToProperties(e, t);
        if (t.properties._paintedByParent) getImageFromServer(e, t);
        s++;
      }
    } else if (o == "Height" && !isRectangularControl(e, t)) {
      if (!isControlLocked(e, t.properties.Name)) {
        if (t.properties.Y2 >= t.properties.Y1) {
          t.properties.Y2 = t.properties.Y1 + n;
        } else {
          t.properties.Y1 = t.properties.Y2 + n;
        }
        syncDesignerControlToProperties(e, t);
        if (t.properties._paintedByParent) getImageFromServer(e, t);
        s++;
      }
    } else {
      if (t.properties[o] !== n) {
        if (r && isControlLocked(e, t.properties.Name)) {
        } else if (i && t.properties.Dock !== e.tbDockNone) {
        } else {
          t.properties[o] = n;
          syncDesignerControlToProperties(e, t);
          s++;
          if (o === "Dock" || (r && t.properties.Dock !== e.tbDockNone)) {
            doAnchoringAdjustments(e, t.parentElement, true);
          }
          if (r || t.properties._paintedByParent) {
            getImageFromServer(e, t);
          }
        }
      }
    }
  });
  if (s > 0) undoPoint(e);
}
function mergeDeep(e, t, o) {
  for (const i in o) {
    if (Array.isArray(o[i])) {
      if (t[i] === undefined || t[i] === null) {
        t[i] = [];
      }
      if (isObject(o[i])) {
        while (t[i].length < o[i].length) {
          t[i].push({});
        }
        var n = 0;
        o[i].forEach((o) => {
          mergeDeep(e, t[i][n++], o);
        });
      } else {
        while (t[i].length < o[i].length) {
          t[i].push(undefined);
        }
        var n = 0;
        o[i].forEach((e) => {
          if (t[i][n] === undefined || t[i][n] === o[i][n]) {
            t[i][n++] = e;
          } else {
            t[i][n++] = null;
          }
        });
      }
    } else if (o[i] !== null && typeof o[i] === "object") {
      if (t[i] === undefined) {
        t[i] = {};
      }
      mergeDeep(e, t[i], o[i]);
    } else {
      if (t[i] === undefined) {
        t[i] = o[i];
      } else if (t[i] === o[i]) {
      } else {
        t[i] = null;
      }
    }
  }
}
function fixupEventInfo(e, t, o) {
  var n = t.properties.__events[o];
  if (n.StartLine !== undefined) {
    t.properties.__events[o] = {
      Uri: t.properties.__events_Uri,
      StartLine: n.StartLine,
      StartCharIndex: n.NewEvent ? n.StartCharIndex : -1,
      EndLine: n.EndLine,
      EndCharIndex: n.EndCharIndex,
      Proc: n.Proc,
      NewEvent: n.NewEvent,
      Unimplemented: n.Unimplemented,
    };
  } else {
    t.properties.__events[o] = {
      Uri: t.properties.__events_Uri,
      StartLine: t.properties.__events_InsertLine,
      StartCharIndex: t.properties.__events_InsertCharIndex,
      NewEvent: n.NewEvent,
      Unimplemented: n.Unimplemented,
    };
  }
  return t.properties.__events[o];
}
function PropertySortFunction(e, t) {
  e = e.toLowerCase();
  t = t.toLowerCase();
  if (e === "name") return -1;
  if (t === "name") return 1;
  if (e < t) {
    return -1;
  }
  if (e > t) {
    return 1;
  }
  return 0;
}
function syncPropertySheet(e) {
  e.gpOuter.style.visibility = "hidden";
  e.gpOuter.style.display = "none";
  e.propertySheet.innerHTML = "";
  var t = {};
  var o = [];
  e.selectedControls.forEach((n) => {
    if (n.serverErrorInfo) {
      o.push("&#9888; " + n.serverErrorInfo);
    }
    {
      var i = n.properties.ScaleMode;
      var r =
        n.parentNode && n.parentNode.properties
          ? n.parentNode.properties.ScaleMode
          : undefined;
      var s;
      var a;
      var l;
      var d;
      if (r) {
        s = n.parentNode.properties.ScaleWidth / n.parentNode.properties.Width;
        a =
          n.parentNode.properties.ScaleHeight / n.parentNode.properties.Height;
        l = n.parentNode.properties.ScaleLeft;
        d = n.parentNode.properties.ScaleTop;
        if (r == "vbPixels" && e.designer.properties.__dpi == 96) {
          s = 1;
          a = 1;
        }
      } else {
        r = "vbTwips";
        s = 15;
        a = 15;
        l = 0;
        d = 0;
        if (i == "vbPixels" && e.designer.properties.__dpi == 96) {
          n.properties.ScaleWidth = n.properties.Width;
          n.properties.ScaleHeight = n.properties.Height;
        }
      }
      if (n.properties.Left != undefined) {
        n.properties.__scaleFactor_Left = s;
        n.properties.__scaleOffset_Left = l;
        n.properties.__customDesigner_Left = "designer_scaleMode_" + r;
      }
      if (n.properties.Top != undefined) {
        n.properties.__scaleFactor_Top = a;
        n.properties.__scaleOffset_Top = d;
        n.properties.__customDesigner_Top = "designer_scaleMode_" + r;
      }
      if (n.properties.Width != undefined) {
        n.properties.__scaleFactor_Width = s;
        n.properties.__customDesigner_Width = "designer_scaleMode_" + r;
      }
      if (n.properties.Height != undefined) {
        n.properties.__scaleFactor_Height = a;
        n.properties.__customDesigner_Height = "designer_scaleMode_" + r;
      }
      if (n.properties.X1 != undefined) {
        n.properties.__scaleFactor_X1 = s;
        n.properties.__scaleOffset_X1 = l;
        n.properties.__customDesigner_X1 = "designer_scaleMode_" + r;
      }
      if (n.properties.Y1 != undefined) {
        n.properties.__scaleFactor_Y1 = a;
        n.properties.__scaleOffset_Y1 = d;
        n.properties.__customDesigner_Y1 = "designer_scaleMode_" + r;
      }
      if (n.properties.X2 != undefined) {
        n.properties.__scaleFactor_X2 = s;
        n.properties.__scaleOffset_X2 = l;
        n.properties.__customDesigner_X2 = "designer_scaleMode_" + r;
      }
      if (n.properties.Y2 != undefined) {
        n.properties.__scaleFactor_Y2 = a;
        n.properties.__scaleOffset_Y2 = d;
        n.properties.__customDesigner_Y2 = "designer_scaleMode_" + r;
      }
      if (n.properties.ScaleLeft != undefined && i) {
        n.properties.__customDesigner_ScaleLeft = "designer_scaleMode_" + i;
      }
      if (n.properties.ScaleTop != undefined && i) {
        n.properties.__customDesigner_ScaleTop = "designer_scaleMode_" + i;
      }
      if (n.properties.ScaleWidth != undefined && i) {
        n.properties.__customDesigner_ScaleWidth = "designer_scaleMode_" + i;
      }
      if (n.properties.ScaleHeight != undefined && i) {
        n.properties.__customDesigner_ScaleHeight = "designer_scaleMode_" + i;
      }
    }
    var c;
    if (e.toolbarProperties.classList.contains("selected")) {
      c = n.properties;
    } else {
      if (e.selectedControls.length == 1) {
        c = {};
        if (n.properties.__events === undefined) {
          n.properties.__events = {};
        }
        for (var u of Object.keys(n.properties.__events)) {
          var p = fixupEventInfo(e, n, u);
          c[u] =
            p.Proc !== undefined
              ? "<span class='treeObject'>" + p.Proc + "() ...</span>"
              : "";
          c["__customDesigner_" + u] = "designer_Event";
          if (p.Unimplemented) c["__unimpl_" + u] = true;
        }
      }
    }
    mergeDeep(e, t, c);
  });
  if (o.length > 0) {
    var n = o.join("<br/>");
    var i = document.createElement("div");
    i.className = "errorInfoPropertySheet";
    i.innerHTML = n;
    e.propertySheet.appendChild(i);
  }
  t = Object.keys(t)
    .sort(PropertySortFunction)
    .reduce(function (e, o) {
      e[o] = t[o];
      return e;
    }, {});
  createPropertySheet(e, undefined, e.propertySheet, t, 0);
  if (e.selectedControls.length == 1) {
    e.selectedControls[0].controlSelecterOption.selected = true;
    e.allControls.forEach((e) => {
      e.controlSelecterOption.hidden = false;
    });
    e.designer.controlSelecterOption.hidden = false;
  } else {
    e.controlSelecter.selectedIndex = 1;
    e.allControls.forEach((e) => {
      e.controlSelecterOption.hidden = !e.isSelected;
    });
    e.designer.controlSelecterOption.hidden = true;
  }
  if (e.restorePropertiesBoxScroll) {
    e.propertiesBoxInner.scrollTop = e.restorePropertiesBoxScroll;
  }
}
function changeToolboxSelectedItem(e) {
  e.allToolboxItems.forEach((e) => {
    e.classList.remove("toolBoxItemSelected");
  });
  e.selectedTool.classList.add("toolBoxItemSelected");
  if (e.selectedTool === e.toolBoxPointer) {
    e.designerContainer.style.cursor = "default";
  } else {
    e.designerContainer.style.cursor = "crosshair";
  }
  stopFlashing(e);
}
function document_onkeyup(e, t) {
  if (t.key === "Control") {
    e.designer.classList.remove("designerShowTabIndex");
  }
}
function document_onkeydown(e, t) {
  if (e.propertyValueEditor !== undefined) return;
  var o = e.alignToGrid ? e.alignToGridX : 1;
  var n = e.alignToGrid ? e.alignToGridY : 1;
  if (t.key === "Control") {
    e.designer.classList.add("designerShowTabIndex");
  } else if (t.key === "ArrowLeft") {
    if (t.ctrlKey && t.shiftKey) {
      resizeControlsNarrowest(e, e.selectedControls);
    } else if (t.altKey) {
      alignControlsLeft(e, e.selectedControls);
    } else if (t.shiftKey) {
      resizeControls(e, e.selectedControls, -o, 0);
      StoreSelectedControlsLastPositions(e);
      syncFormDragPoints(e);
    } else {
      moveControls(e, e.selectedControls, -o, 0);
      StoreSelectedControlsLastPositions(e);
    }
    t.preventDefault();
  } else if (t.key === "ArrowRight") {
    if (t.ctrlKey && t.shiftKey) {
      resizeControlsWidest(e, e.selectedControls);
    } else if (t.altKey) {
      alignControlsRight(e, e.selectedControls);
    } else if (t.shiftKey) {
      resizeControls(e, e.selectedControls, o, 0);
      StoreSelectedControlsLastPositions(e);
      syncFormDragPoints(e);
    } else {
      moveControls(e, e.selectedControls, o, 0);
      StoreSelectedControlsLastPositions(e);
    }
    t.preventDefault();
  } else if (t.key === "ArrowUp") {
    if (t.ctrlKey && t.shiftKey) {
      resizeControlsShortest(e, e.selectedControls);
    } else if (t.altKey) {
      alignControlsTop(e, e.selectedControls);
    } else if (t.shiftKey) {
      resizeControls(e, e.selectedControls, 0, -n);
      StoreSelectedControlsLastPositions(e);
      syncFormDragPoints(e);
    } else {
      moveControls(e, e.selectedControls, 0, -n);
      StoreSelectedControlsLastPositions(e);
    }
    t.preventDefault();
  } else if (t.key === "ArrowDown") {
    if (t.ctrlKey && t.shiftKey) {
      resizeControlsTallest(e, e.selectedControls);
    } else if (t.altKey) {
      alignControlsBottom(e, e.selectedControls);
    } else if (t.shiftKey) {
      resizeControls(e, e.selectedControls, 0, n);
      StoreSelectedControlsLastPositions(e);
      syncFormDragPoints(e);
    } else {
      moveControls(e, e.selectedControls, 0, n);
      StoreSelectedControlsLastPositions(e);
    }
    t.preventDefault();
  } else if (t.key === "删除") {
    deleteSelectedControls(e);
    undoPoint(e);
    onSignificantChange(e);
  } else if (t.key === "Escape") {
    if (e.IgnoringEscapeKey) return;
    e.toolBoxPointer.onclick();
    changeToolboxSelectedItem(e);
    stopFlashing(e);
    if (e.selectedControls.length > 0) {
      var i = e.selectedControls[0];
      unselectAllControls(e);
      if (i !== e.designer) {
        e.designer.isSelected = false;
        e.selectedControls = [i.parentElement];
        changedSelectedControls(e);
        StoreSelectedControlsLastPositions(e);
        syncFormDragPoints(e);
      }
      syncPropertySheet(e);
    }
  } else if (t.ctrlKey && t.key == "a") {
    e.selectedControls = e.allControls.filter(() => true);
    changedSelectedControls(e);
    StoreSelectedControlsLastPositions(e);
  } else if (t.key === "Control") {
    if (e.currentFlashingContainer !== undefined) {
      if (e.currentFlashingContainer !== e.designer) {
        stopFlashing(e);
        e.currentFlashingContainer = e.designerContainer;
        e.currentFlashingContainer.classList.add("boxShadowRed");
      }
    }
  } else {
  }
}
function deleteControl(e, t) {
  if (t === e.designer || t === e.designerContainer) {
    return;
  }
  if (t.menuControl && t.parentNode === e.designer) {
    e.designerMenuBar.removeChild(t.menuControl);
  }
  if (t.lastImageRequestId) {
    e.outstandingSerializationRequests--;
    t.lastImageRequestId = undefined;
  } else {
  }
  if (t.isDeleted) return;
  t.isDeleted = true;
  t.classList.remove("hasLockedIcon");
  if (t.draggerTopLeft !== undefined) {
    t.draggerTopLeft.parentElement.removeChild(t.draggerTopLeft);
    t.draggerTopLeft = undefined;
  }
  if (t.draggerTop !== undefined) {
    t.draggerTop.parentElement.removeChild(t.draggerTop);
    t.draggerTop = undefined;
  }
  if (t.draggerTopRight !== undefined) {
    t.draggerTopRight.parentElement.removeChild(t.draggerTopRight);
    t.draggerTopRight = undefined;
  }
  if (t.draggerLeft !== undefined) {
    t.draggerLeft.parentElement.removeChild(t.draggerLeft);
    t.draggerLeft = undefined;
  }
  if (t.draggerRight !== undefined) {
    t.draggerRight.parentElement.removeChild(t.draggerRight);
    t.draggerRight = undefined;
  }
  if (t.draggerBottomLeft !== undefined) {
    t.draggerBottomLeft.parentElement.removeChild(t.draggerBottomLeft);
    t.draggerBottomLeft = undefined;
  }
  if (t.draggerBottom !== undefined) {
    t.draggerBottom.parentElement.removeChild(t.draggerBottom);
    t.draggerBottom = undefined;
  }
  if (t.draggerBottomRight !== undefined) {
    t.draggerBottomRight.parentElement.removeChild(t.draggerBottomRight);
    t.draggerBottomRight = undefined;
  }
  var o = t.parentElement;
  o.removeChild(t);
  doAnchoringAdjustments(e, o, true);
  t.controlSelecterOption.associatedControl = undefined;
  if (
    e.controlSelecter.options[e.controlSelecter.selectedIndex] ===
    t.controlSelecterOption
  ) {
    e.formSelectorOption.selected = true;
    e.selectedControls = [e.designer];
    changedSelectedControls(e);
    e.designer.isSelected = true;
  }
  if (t.controlSelecterOption)
    e.controlSelecter.removeChild(t.controlSelecterOption);
  if (t.children.length > 0) {
    var n = Array.prototype.slice.call(t.children, 0);
    n.forEach((t) => {
      deleteControl(e, t);
    });
  }
  const i = e.allControls.indexOf(t);
  if (i > -1) e.allControls.splice(i, 1);
  unlockTheControl(e, t.properties.Name, true);
  if (o !== e.designerContainer) {
    addPendingControl(e, o);
  }
}
function deleteSelectedControls(e) {
  e.selectedControls.forEach((t) => {
    deleteControl(e, t);
  });
  if (e.dontHidePopupMenus) return;
  if (e.formSelectorOption !== undefined && e.formSelectorOption !== null)
    e.formSelectorOption.selected = true;
  e.selectedControls = [e.designer];
  changedSelectedControls(e);
  StoreSelectedControlsLastPositions(e);
  refreshPendingControls(e);
}
function document_oncut(e, t) {
  if (e.licenceOverlay.style.visibility === "visible") return;
  if (e.propertyValueEditor !== undefined) return;
  document_oncopy(e, t);
  deleteSelectedControls(e);
  undoPoint(e);
  onSignificantChange(e);
}
function document_oncopy(e, t) {
  if (e.licenceOverlay.style.visibility === "visible") return;
  if (e.propertyValueEditor !== undefined) return;
  var o = JSON.stringify(serializeControls(e, e.selectedControls));
  e.vscode.postMessage({ type: "clipboardCopy", args: [o] });
  if (t) t.preventDefault();
}
function preparePaste(e) {
  var t = {};
  t.lowestPointOfSelection = { x: 0, y: 0 };
  if (e.selectedControls.length > 0) {
    t.lowestPointOfSelection = getLowestPointOfControls(e, e.selectedControls);
  }
  t.parentContainer = e.designer;
  t.wasContainerSelection = false;
  if (e.selectedControls.length > 0) {
    if (
      e.selectedControls[0].properties._clsid ==
        "{E6E927FA-F6E6-4E8E-9540-DA8696F38429}" ||
      e.selectedControls[0].properties._isFrame
    ) {
      t.parentContainer = e.selectedControls[0];
      if (e.selectedControls.length == 1) t.wasContainerSelection = true;
    } else if (e.selectedControls[0] === e.designer) {
      t.wasContainerSelection = true;
    } else {
      t.parentContainer = e.selectedControls[0].parentElement;
    }
  }
  if (t.parentContainer === e.designerContainer) t.parentContainer = e.designer;
  t.wasNoSelection =
    e.selectedControls.length == 1 && e.selectedControls[0] === e.designer;
  unselectAllControls(e);
  return t;
}
function doPaste(e, t, o, n) {
  if (n && o.length === 1) {
    let n = o[0];
    if (n.properties._isFrame && t.wasContainerSelection) {
      t.wasContainerSelection = false;
      n.parentNode.removeChild(n);
      e.designer.appendChild(n);
    }
  }
  e.selectedControls = o;
  changedSelectedControls(e);
  e.selectedControls.forEach((e) => {
    e.classList.add("baseControlSelected");
    e.isSelected = true;
  });
  var i = getTopLeftOfAllControls(e, e.selectedControls);
  if (t.wasContainerSelection) {
    var r = t.parentContainer;
    var s = 0;
    var a = 0;
    while (r !== e.designer) {
      s += r.offsetLeft;
      a += r.offsetTop;
      r = r.parentElement;
    }
    moveControls(e, e.selectedControls, s - i.x, a - i.y);
  } else if (t.wasNoSelection) {
    moveControls(
      e,
      e.selectedControls,
      -(i.x - e.designerContainer.offsetLeft),
      -(i.y - e.designerContainer.offsetTop)
    );
  } else {
    moveControls(
      e,
      e.selectedControls,
      t.lowestPointOfSelection.x - i.x,
      t.lowestPointOfSelection.y - i.y + 10
    );
  }
  StoreSelectedControlsLastPositions(e);
  doAnchoringAdjustments(e, t.parentContainer, true);
  onSignificantChange(e);
}
function document_onpaste(e, t, o) {
  var n = e.selectedControls;
  if (e.licenceOverlay.style.visibility === "visible") return;
  if (e.propertyValueEditor !== undefined) return;
  var i = preparePaste(e);
  e.vscode.postMessage({ type: "getClipboardData", args: ["text/tbControls"] });
  e.gotClipboardDataFunction = (t) => {
    debugger;
    var r;
    try {
      r = JSON.parse(t);
      if (Array.isArray(r)) {
        if (r.length === 1) {
          if (r[0]._className === "Menu") {
            var s = undefined;
            if (n.length === 1) {
              if (n[0].properties._className === "Menu") {
                s = n[0];
              }
            }
            pasteIntoMenu(e, s ? s : e.designer, t);
            return;
          }
        }
      }
      e.selectedControls = deserializeControls(
        e,
        t,
        i.parentContainer,
        false,
        o
      );
      changedSelectedControls(e);
      doPaste(e, i, e.selectedControls, false);
    } catch (e) {}
  };
  if (t) t.preventDefault();
}
function alignControlsLeft(e, t) {
  var o = 0;
  var n = getTopLeftOfAllControls(e, t);
  t.forEach((t) => {
    if (isControlLocked(e, t.properties.Name)) return;
    if (isRectangularControl(e, t)) {
      if (t.properties.Dock === e.tbDockNone) {
        var i = t.parentElement;
        var r = 0;
        while (i !== e.designer) {
          r += i.offsetLeft;
          i = i.parentElement;
        }
        var s = n.x - r;
        if (t.properties.Left != s) {
          t.properties.Left = s;
          syncDesignerControlToProperties(e, t);
          if (t.properties._paintedByParent) getImageFromServer(e, t);
          o++;
        }
      }
    } else {
      var i = t.parentElement;
      var r = 0;
      while (i !== e.designer) {
        r += i.offsetLeft;
        i = i.parentElement;
      }
      var s = n.x - r;
      if (t.properties.X2 >= t.properties.X1) {
        if (t.properties.X1 != s) {
          t.properties.X2 -= t.properties.X1 - s;
          t.properties.X1 = s;
          syncDesignerControlToProperties(e, t);
          if (t.properties._paintedByParent) getImageFromServer(e, t);
          o++;
        }
      } else {
        if (t.properties.X2 != s) {
          t.properties.X1 -= t.properties.X2 - s;
          t.properties.X2 = s;
          syncDesignerControlToProperties(e, t);
          if (t.properties._paintedByParent) getImageFromServer(e, t);
          o++;
        }
      }
    }
  });
  StoreSelectedControlsLastPositions(e);
  if (o > 0) undoPoint(e);
}
function alignControlsRight(e, t) {
  var o = 0;
  var n = getTopRightOfAllControls(e, t);
  t.forEach((t) => {
    if (isControlLocked(e, t.properties.Name)) return;
    if (isRectangularControl(e, t)) {
      if (t.properties.Dock === e.tbDockNone) {
        var i = t.parentElement;
        var r = 0;
        while (i !== e.designer) {
          r += i.offsetLeft;
          i = i.parentElement;
        }
        var s = n.x - r - t.offsetWidth;
        if (t.properties.Left != s) {
          t.properties.Left = s;
          syncDesignerControlToProperties(e, t);
          if (t.properties._paintedByParent) getImageFromServer(e, t);
          o++;
        }
      }
    } else {
      var i = t.parentElement;
      var r = 0;
      while (i !== e.designer) {
        r += i.offsetLeft;
        i = i.parentElement;
      }
      var s = n.x - r - Math.abs(t.properties.X2 - t.properties.X1);
      if (t.properties.X2 >= t.properties.X1) {
        if (t.properties.X1 != s) {
          t.properties.X2 -= t.properties.X1 - s;
          t.properties.X1 = s;
          syncDesignerControlToProperties(e, t);
          if (t.properties._paintedByParent) getImageFromServer(e, t);
          o++;
        }
      } else {
        if (t.properties.X2 != s) {
          t.properties.X1 -= t.properties.X2 - s;
          t.properties.X2 = s;
          syncDesignerControlToProperties(e, t);
          if (t.properties._paintedByParent) getImageFromServer(e, t);
          o++;
        }
      }
    }
  });
  StoreSelectedControlsLastPositions(e);
  if (o > 0) undoPoint(e);
}
function alignControlsTop(e, t) {
  var o = 0;
  var n = getTopRightOfAllControls(e, t);
  t.forEach((t) => {
    if (isControlLocked(e, t.properties.Name)) return;
    if (isRectangularControl(e, t)) {
      if (t.properties.Dock === e.tbDockNone) {
        var i = t.parentElement;
        var r = 0;
        while (i !== e.designer) {
          r += i.offsetTop;
          i = i.parentElement;
        }
        var s = n.y - r;
        if (t.properties.Top != s) {
          t.properties.Top = s;
          syncDesignerControlToProperties(e, t);
          if (t.properties._paintedByParent) getImageFromServer(e, t);
          o++;
        }
      }
    } else {
      var i = t.parentElement;
      var r = 0;
      while (i !== e.designer) {
        r += i.offsetTop;
        i = i.parentElement;
      }
      var s = n.y - r;
      if (t.properties.Y2 >= t.properties.Y1) {
        if (t.properties.Y1 != s) {
          t.properties.Y2 -= t.properties.Y1 - s;
          t.properties.Y1 = s;
          syncDesignerControlToProperties(e, t);
          if (t.properties._paintedByParent) getImageFromServer(e, t);
          o++;
        }
      } else {
        if (t.properties.Y2 != s) {
          t.properties.Y1 -= t.properties.Y2 - s;
          t.properties.Y2 = s;
          syncDesignerControlToProperties(e, t);
          if (t.properties._paintedByParent) getImageFromServer(e, t);
          o++;
        }
      }
    }
  });
  StoreSelectedControlsLastPositions(e);
  if (o > 0) undoPoint(e);
}
function alignControlsBottom(e, t) {
  var o = 0;
  var n = getLowestPointOfControls(e, t);
  t.forEach((t) => {
    if (isControlLocked(e, t.properties.Name)) return;
    if (isRectangularControl(e, t)) {
      if (t.properties.Dock === e.tbDockNone) {
        var i = t.parentElement;
        var r = 0;
        while (i != e.designer) {
          r += i.offsetTop;
          i = i.parentElement;
        }
        var s = n.y - r - t.offsetHeight;
        if (t.properties.Top != s) {
          t.properties.Top = s;
          syncDesignerControlToProperties(e, t);
          if (t.properties._paintedByParent) getImageFromServer(e, t);
          o++;
        }
      }
    } else {
      var i = t.parentElement;
      var r = 0;
      while (i != e.designer) {
        r += i.offsetTop;
        i = i.parentElement;
      }
      var s = n.y - r - Math.abs(t.properties.Y2 - t.properties.Y1);
      if (t.properties.Y2 >= t.properties.Y1) {
        if (t.properties.Y1 != s) {
          t.properties.Y2 -= t.properties.Y1 - s;
          t.properties.Y1 = s;
          syncDesignerControlToProperties(e, t);
          if (t.properties._paintedByParent) getImageFromServer(e, t);
          o++;
        }
      } else {
        if (t.properties.Y2 != s) {
          t.properties.Y1 -= t.properties.Y2 - s;
          t.properties.Y2 = s;
          syncDesignerControlToProperties(e, t);
          if (t.properties._paintedByParent) getImageFromServer(e, t);
          o++;
        }
      }
    }
  });
  StoreSelectedControlsLastPositions(e);
  if (o > 0) undoPoint(e);
}
function getWidestControlSize(e, t) {
  var o = 0;
  t.forEach((t) => {
    if (isRectangularControl(e, t)) {
      if (t.clientWidth > o) {
        o = t.clientWidth;
      }
    } else {
      let e = Math.abs(t.properties.X2 - t.properties.X1);
      if (e > o) {
        o = e;
      }
    }
  });
  return o;
}
function resizeControlsWidest(e, t) {
  var o = getWidestControlSize(e, t);
  setArrayCommonPropertyValue(e, t, "Width", o, false, true);
  StoreSelectedControlsLastPositions(e);
}
function getNarrowestControlSize(e, t) {
  var o = -1;
  t.forEach((t) => {
    if (isRectangularControl(e, t)) {
      if (t.clientWidth < o || o == -1) {
        o = t.clientWidth;
      }
    } else {
      let e = Math.abs(t.properties.X2 - t.properties.X1);
      if (e < o || o == -1) {
        o = e;
      }
    }
  });
  return o;
}
function resizeControlsNarrowest(e, t) {
  var o = getNarrowestControlSize(e, t);
  setArrayCommonPropertyValue(e, t, "Width", o, false, true);
  StoreSelectedControlsLastPositions(e);
}
function getTallestControlSize(e, t) {
  var o = 0;
  t.forEach((t) => {
    if (isRectangularControl(e, t)) {
      if (t.clientHeight > o) {
        o = t.clientHeight;
      }
    } else {
      let e = Math.abs(t.properties.Y2 - t.properties.Y1);
      if (e > o) {
        o = e;
      }
    }
  });
  return o;
}
function resizeControlsTallest(e, t) {
  var o = getTallestControlSize(e, t);
  setArrayCommonPropertyValue(e, t, "Height", o, false, true);
  StoreSelectedControlsLastPositions(e);
}
function getShortestControlSize(e, t) {
  var o = -1;
  t.forEach((t) => {
    if (isRectangularControl(e, t)) {
      if (t.clientHeight < o || o == -1) {
        o = t.clientHeight;
      }
    } else {
      let e = Math.abs(t.properties.Y2 - t.properties.Y1);
      if (e < o || o == -1) {
        o = e;
      }
    }
  });
  return o;
}
function resizeControlsShortest(e, t) {
  var o = getShortestControlSize(e, t);
  setArrayCommonPropertyValue(e, t, "Height", o, false, true);
  StoreSelectedControlsLastPositions(e);
}
function resizeControls(e, t, o, n) {
  if (o != 0 || n != 0) {
    t.forEach((t) => {
      if (isControlLocked(e, t.properties.Name)) return;
      if (t.properties.Dock !== e.tbDockFill) {
        if (
          t.properties.Dock !== e.tbDockTop &&
          t.properties.Dock !== e.tbDockBottom
        ) {
          if (isRectangularControl(e, t)) {
            t.properties.Width += o;
            if (e.alignToGrid) {
              var i = t.properties.Width % e.alignToGridX;
              if (i) t.properties.Width -= i;
            }
          } else {
            if (t.properties.X2 > t.properties.X1) {
              t.properties.X2 += o;
              if (e.alignToGrid) {
                var i = t.properties.X2 % e.alignToGridX;
                if (i) t.properties.X2 -= i;
              }
            } else {
              t.properties.X1 += o;
              if (e.alignToGrid) {
                var i = t.properties.X1 % e.alignToGridX;
                if (i) t.properties.X1 -= i;
              }
            }
          }
        }
        if (
          t.properties.Dock !== e.tbDockLeft &&
          t.properties.Dock !== e.tbDockRight
        ) {
          if (isRectangularControl(e, t)) {
            t.properties.Height += n;
            if (e.alignToGrid) {
              var r = t.properties.Height % e.alignToGridY;
              if (r) t.properties.Height -= r;
            }
          } else {
            if (t.properties.Y2 > t.properties.Y1) {
              t.properties.Y2 += n;
              if (e.alignToGrid) {
                var r = t.properties.Y2 % e.alignToGridY;
                if (r) t.properties.Y2 -= r;
              }
            } else {
              t.properties.Y1 += n;
              if (e.alignToGrid) {
                var r = t.properties.Y1 % e.alignToGridY;
                if (r) t.properties.Y1 -= r;
              }
            }
          }
        }
      }
      getImageFromServer(e, t);
      syncDesignerControlToProperties(e, t);
      doAnchoringAdjustments(e, t, true);
      if (t.properties.Dock !== undefined && t.properties.Dock !== e.tbDockNone)
        doAnchoringAdjustments(e, t.parentElement, true);
    });
    undoPoint(e);
  }
}
function moveControls(e, t, o, n) {
  if (o != 0 || n != 0) {
    calculateInclusionCount(e, t);
    t.forEach((t) => {
      if (isControlLocked(e, t.properties.Name)) return;
      if (t.InclusionCount == 1) {
        if (
          t.properties.Dock !== undefined &&
          t.properties.Dock != e.tbDockNone
        ) {
        } else {
          if (isRectangularControl(e, t)) {
            t.properties.Left += o;
            t.properties.Top += n;
            if (e.alignToGrid) {
              var i = t.properties.Left % e.alignToGridX;
              var r = t.properties.Top % e.alignToGridY;
              if (i) t.properties.Left -= i;
              if (r) t.properties.Top -= r;
            }
          } else if (selectedControl.properties._className === "Menu") {
          } else {
            t.properties.X1 += o;
            t.properties.Y1 += n;
            t.properties.X2 += o;
            t.properties.Y2 += n;
            if (e.alignToGrid) {
              var i = t.properties.X1 % e.alignToGridX;
              var r = t.properties.Y1 % e.alignToGridY;
              if (i) t.properties.X1 -= i;
              if (r) t.properties.Y1 -= r;
              if (i) t.properties.X2 -= i;
              if (r) t.properties.Y2 -= r;
            }
          }
          syncDesignerControlToProperties(e, t);
          if (t.properties._paintedByParent) getImageFromServer(e, t);
        }
      }
    });
    undoPoint(e);
  }
}
function moveControlsTopLeft(e, t) {
  t.forEach((t) => {
    if (isControlLocked(e, t.properties.Name)) return;
    if (t.properties.Dock !== undefined && t.properties.Dock != e.tbDockNone) {
    } else {
      t.properties.Left = 0;
      t.properties.Top = 0;
      syncDesignerControlToProperties(e, t);
      if (t.properties._paintedByParent) getImageFromServer(e, t);
    }
  });
  undoPoint(e);
}
function getLowestPointOfControls(e, t) {
  var o = -1;
  var n = 0;
  t.forEach((t) => {
    var i = getControlRectOffsetToDesigner(e, t);
    if (i.left < o || o == -1) {
      o = i.left;
    }
    if (i.bottom > n) {
      n = i.bottom;
    }
  });
  return { x: o, y: n };
}
function getControlRectOffsetToDesigner(e, t) {
  var o;
  if (isRectangularControl(e, t)) {
    o = {
      left: t.offsetLeft,
      top: t.offsetTop,
      right: t.offsetLeft + t.offsetWidth,
      bottom: t.offsetTop + t.offsetHeight,
    };
    if (t === e.designer) {
      return { left: 0, top: 0, right: t.offsetWidth, bottom: t.offsetheight };
    }
  } else {
    o = {
      left: t.properties.X1,
      top: t.properties.Y1,
      right: t.properties.X2,
      bottom: t.properties.Y2,
    };
    if (o.right < o.left) {
      let e = o.left;
      o.left = o.right;
      o.right = e;
    }
    if (o.bottom < o.top) {
      let e = o.top;
      o.top = o.bottom;
      o.bottom = e;
    }
  }
  t = t.parentElement;
  while (t !== e.designer) {
    o.left += t.offsetLeft;
    o.top += t.offsetTop;
    o.right += t.offsetLeft;
    o.bottom += t.offsetTop;
    t = t.parentElement;
  }
  return o;
}
function getTopLeftOfAllControls(e, t) {
  var o = -1;
  var n = -1;
  t.forEach((t) => {
    var i = getControlRectOffsetToDesigner(e, t);
    if (i.top < n || n == -1) {
      n = i.top;
    }
    if (i.left < o || o == -1) {
      o = i.left;
    }
  });
  return { x: o, y: n };
}
function getTopRightOfAllControls(e, t) {
  var o = 0;
  var n = -1;
  t.forEach((t) => {
    var i = getControlRectOffsetToDesigner(e, t);
    if (i.top < n || n == -1) {
      n = i.top;
    }
    if (i.right > o) {
      o = i.right;
    }
  });
  return { x: o, y: n };
}
function addPendingControl(e, t) {
  if (t && !t.isPendingRefresh && t !== e.designerContainer) {
    t.isPendingRefresh = true;
    e.pendingControlRefreshes.push(t);
  }
}
function refreshPendingControls(e) {
  var t = e.pendingControlRefreshes;
  e.pendingControlRefreshes = [];
  t.forEach((t) => {
    t.isPendingRefresh = false;
    if (!t.isDeleted) getImageFromServer(e, t);
  });
}
function getControlFromProperties(e, t, o, n, i, r) {
  var s;
  if (
    t._clsid == formCLSID_Custom ||
    t._clsid == formCLSID_Windows ||
    t._clsid == formCLSID_WindowsUserControl ||
    t._clsid == formCLSID_WindowsPropertyPage
  ) {
    s = e.designer;
  } else {
    let n = t._className.split(".");
    let i = n.pop();
    let r = n.length > 0 ? n.pop() : undefined;
    if (r === undefined) r = "VB";
    s = addControl(e, i, o, t.clsid, r);
    addPendingControl(e, o);
  }
  for (const o in t) {
    if (o == "Name") {
      if (r || n) {
        s.properties.Name = t[o];
      }
    } else if (o == "Index") {
      if (r) {
        s.properties.Index = getControlArrayMaxIndex(e, s.properties.Name) + 1;
      } else {
        if (n) {
          s.properties.Index = t[o];
        } else {
          s.properties.Index = -1;
        }
      }
    } else if (o == "TabIndex") {
      if (n) {
        s.properties.TabIndex = t[o];
      }
    } else if (o == "_children") {
      var a = t["_children"];
      a.forEach((t) => {
        getControlFromProperties(e, t, s, n, i);
      });
    } else {
      s.properties[o] = t[o];
    }
  }
  if (!n && s.properties._isExclusiveWithinContainer) {
    s.properties.Value = false;
  }
  if (i) s.isInitializing = true;
  addPendingControl(e, s);
  syncDesignerControlToProperties(e, s);
  doAnchoringAdjustments(e, s, true);
  if (
    t._clsid == formCLSID_Custom ||
    t._clsid == formCLSID_Windows ||
    t._clsid == formCLSID_WindowsUserControl ||
    t._clsid == formCLSID_WindowsPropertyPage
  ) {
    syncFormDragPoints(e);
  }
  return s;
}
function getControlPropertiesArray(e, t, o) {
  var n = [];
  t.forEach((t) => {
    if (o && t.InclusionCount > 1) {
    } else {
      var i = JSON.parse(JSON.stringify(t.properties, replacer));
      var r = Object.assign({}, i);
      n.push(r);
      t.lastCachedProperties = r;
      if (t.children.length > 0) {
        var s = Array.prototype.slice.call(t.children, 0);
        r._children = getControlPropertiesArray(e, s, false);
      }
    }
  });
  return n;
}
function calculateInclusionCount(e, t, o) {
  if (o === undefined) {
    o = e.inclusionCountID++;
  }
  t.forEach((t) => {
    if (t.InclusionCountID !== o) {
      t.InclusionCountID = o;
      t.InclusionCount = 0;
    }
    t.InclusionCount++;
    if (t.children.length > 0) {
      var n = Array.prototype.slice.call(t.children, 0);
      calculateInclusionCount(e, n, o);
    }
  });
}
function serializeControls(e, t) {
  calculateInclusionCount(e, t);
  return getControlPropertiesArray(e, t, true);
}
function generateRandomUpdateMarker() {
  return Math.floor(Math.random() * 4294967295);
}
function serializeForm(e) {
  var t = serializeControls(e, [e.designer]);
  var o = {
    showGrid: e.showGrid,
    alignToGrid: e.alignToGrid,
    showOutlines: e.showOutlines,
    gridWidth: e.alignToGridX,
    gridHeight: e.alignToGridY,
    lockedControls: e.lockedControls,
  };
  if (o.showGrid == undefined) o.showGrid = false;
  if (o.alignToGrid == undefined) o.alignToGrid = false;
  if (o.showOutlines == undefined) o.showOutlines = false;
  if (!o.gridWidth) o.gridWidth = 10;
  if (!o.gridHeight) o.gridHeight = 10;
  if (o.lockedControls === undefined) o.lockedControls = [];
  t[0].__IDEOptions = o;
  t[0].__lastUpdateMarker = generateRandomUpdateMarker();
  return t;
}
function deserializeControls(e, t, o, n, i, r) {
  var s = JSON.parse(t);
  var a = [];
  if (i) {
    s.forEach((t) => {
      debugger;
      var o = getControlByName(e, t.Name);
      if (o && o.properties.Index === -1) {
        changeProperty(e, o, "Index", 0);
        getImageFromServer(e, o);
      }
    });
  }
  s.forEach((t) => {
    var r = getControlFromProperties(e, t, o, n, undefined, i);
    if (r !== undefined) a.push(r);
  });
  refreshPendingControls(e);
  return a;
}
function deserializeForm(e, t) {
  e.allControls = [];
  getControlFromProperties(e, t[0], e.designer, true, true);
  refreshPendingControls(e);
}
function saveFormDesignerEditorConfiguration(e) {
  var t = {
    leftSidePanelWidth: parseInt(e.toolBox.offsetWidth),
    rightSidePanelWidth: parseInt(e.propertiesBox.offsetWidth),
    windowsPalette: e.windowsPalette,
  };
  e.vscode.postMessage({
    type: "onChangedFormDesignerConfiguration",
    args: [t],
  });
}
function toolBoxResizer_onmousedown(e, t) {
  e.toolBox.startDragWidth = e.toolBox.offsetWidth;
  e.toolBox.isResizing = true;
  e.rootElement.onmousemove = (o) => {
    e.toolBox.style.width =
      e.toolBox.startDragWidth + (o.clientX - t.clientX) + "px";
    syncFormDragPoints(e);
    StoreSelectedControlsLastPositions(e);
  };
  e.rootElement.onmouseup2 = (t) => {
    saveFormDesignerEditorConfiguration(e);
    e.toolBox.isResizing = false;
  };
}
function propertiesBoxResizer_onmousedown(e, t) {
  e.propertiesBox.startDragWidth = e.propertiesBox.offsetWidth;
  e.propertiesBox.isResizing = true;
  e.rootElement.onmousemove = (o) => {
    e.propertiesBox.style.width =
      e.propertiesBox.startDragWidth + (t.clientX - o.clientX) + "px";
  };
  e.rootElement.onmouseup2 = (t) => {
    saveFormDesignerEditorConfiguration(e);
    e.propertiesBox.isResizing = false;
  };
}
function doAnchoringAdjustments(e, t, o) {
  var n = t.offsetWidth;
  var i = t.offsetHeight;
  var r = {
    Left: 0,
    Top: 0,
    Width: t.properties.Width,
    Height: t.properties.Height,
  };
  var s = Array.prototype.slice.call(t.children, 0);
  s.forEach((t) => {
    var s = false;
    if (t.properties) {
      if (t.properties.Dock == e.tbDockLeft) {
        if (t.CachedAnchorParentWidth != undefined) {
          if (t.properties.Anchors.Left && t.properties.Anchors.Right) {
            if (!e.WinForms) {
              var a = n - t.CachedAnchorParentWidth;
              if (a) {
                t.properties.Width += a;
                s = true;
              }
            }
          }
        }
        t.properties.Left = r.Left;
        t.properties.Top = r.Top;
        if (t.properties.Height != r.Height) {
          t.properties.Height = r.Height;
          s = true;
        }
        r.Left += t.properties.Width;
        r.Width -= t.properties.Width;
        syncDesignerControlToProperties(e, t);
        if (t.isSelected) {
          removeSelectedControlDragPoints(e, t);
          showSelectedControlDragPoints(e, t);
        }
        if (t.properties._paintedByParent) s = true;
      } else if (t.properties.Dock == e.tbDockTop) {
        if (t.CachedAnchorParentHeight != undefined) {
          if (t.properties.Anchors.Top && t.properties.Anchors.Bottom) {
            if (!e.WinForms) {
              var l = i - t.CachedAnchorParentHeight;
              if (l) {
                t.properties.Height += l;
                s = true;
              }
            }
          }
        }
        t.properties.Left = r.Left;
        t.properties.Top = r.Top;
        if (t.properties.Width != r.Width) {
          t.properties.Width = r.Width;
          s = true;
        }
        r.Top += t.properties.Height;
        r.Height -= t.properties.Height;
        syncUserScaledWidthHeight(e, t);
        syncDesignerControlToProperties(e, t);
        if (t.isSelected) {
          removeSelectedControlDragPoints(e, t);
          showSelectedControlDragPoints(e, t);
        }
        if (t.properties._paintedByParent) s = true;
      } else if (t.properties.Dock == e.tbDockRight) {
        if (t.CachedAnchorParentWidth != undefined) {
          if (t.properties.Anchors.Left && t.properties.Anchors.Right) {
            if (!e.WinForms) {
              var a = n - t.CachedAnchorParentWidth;
              if (a) {
                t.properties.Width += a;
                s = true;
              }
            }
          }
        }
        t.properties.Left = r.Left + r.Width - t.properties.Width;
        t.properties.Top = r.Top;
        if (t.properties.Height != r.Height) {
          t.properties.Height = r.Height;
          s = true;
        }
        r.Width -= t.properties.Width;
        syncDesignerControlToProperties(e, t);
        if (t.isSelected) {
          removeSelectedControlDragPoints(e, t);
          showSelectedControlDragPoints(e, t);
        }
        if (t.properties._paintedByParent) s = true;
      } else if (t.properties.Dock == e.tbDockBottom) {
        if (t.CachedAnchorParentHeight != undefined) {
          if (t.properties.Anchors.Top && t.properties.Anchors.Bottom) {
            if (!e.WinForms) {
              var l = i - t.CachedAnchorParentHeight;
              if (l) {
                t.properties.Height += l;
                s = true;
              }
            }
          }
        }
        t.properties.Left = r.Left;
        t.properties.Top = r.Top + r.Height - t.properties.Height;
        if (t.properties.Width != r.Width) {
          t.properties.Width = r.Width;
          s = true;
        }
        r.Height -= t.properties.Height;
        syncUserScaledWidthHeight(e, t);
        syncDesignerControlToProperties(e, t);
        if (t.isSelected) {
          removeSelectedControlDragPoints(e, t);
          showSelectedControlDragPoints(e, t);
        }
        if (t.properties._paintedByParent) s = true;
      } else if (t.properties.Dock == e.tbDockFill) {
        t.properties.Left = r.Left;
        t.properties.Top = r.Top;
        if (t.properties.Width != r.Width) {
          t.properties.Width = r.Width;
          s = true;
        }
        if (t.properties.Height != r.Height) {
          t.properties.Height = r.Height;
          s = true;
        }
        syncUserScaledWidthHeight(e, t);
        syncDesignerControlToProperties(e, t);
        if (t.isSelected) {
          removeSelectedControlDragPoints(e, t);
          showSelectedControlDragPoints(e, t);
        }
        if (t.properties._paintedByParent) s = true;
      } else {
        if (t.CachedAnchorParentWidth != undefined) {
          if (t.properties.Anchors === undefined) {
          } else if (t.properties.Anchors.Left && t.properties.Anchors.Right) {
            var a = n - t.CachedAnchorParentWidth;
            if (a) {
              t.properties.Width += a;
              s = true;
            }
          } else if (t.properties.Anchors.Left) {
          } else if (t.properties.Anchors.Right) {
            var d = n - t.CachedAnchorParentWidth;
            if (d) {
              t.properties.Left += d;
              s = true;
            }
          } else {
            var d = parseInt(n / 2) - parseInt(t.CachedAnchorParentWidth / 2);
            if (d) {
              t.properties.Left += d;
              s = true;
            }
          }
          if (t.properties.Anchors === undefined) {
          } else if (t.properties.Anchors.Top && t.properties.Anchors.Bottom) {
            var l = i - t.CachedAnchorParentHeight;
            if (l) {
              t.properties.Height += l;
              s = true;
            }
          } else if (t.properties.Anchors.Top) {
          } else if (t.properties.Anchors.Bottom) {
            var c = i - t.CachedAnchorParentHeight;
            if (c) {
              t.properties.Top += c;
              s = true;
            }
          } else {
            var c = parseInt(i / 2) - parseInt(t.CachedAnchorParentHeight / 2);
            if (c) {
              t.properties.Top += c;
              s = true;
            }
          }
        }
      }
      if (s) {
        syncDesignerControlToProperties(e, t, o);
        if (t.isSelected) {
          showSelectedControlDragPoints(e, t);
        }
        getImageFromServer(e, t);
      }
    }
    t.CachedAnchorParentWidth = n;
    t.CachedAnchorParentHeight = i;
  });
}
function jumpToEvent(e, t) {
  if (t.Proc !== undefined) {
    e.vscode.postMessage({
      type: "jumpToFile",
      args: [t.Uri, t.StartLine, t.StartCharIndex, t.EndLine, t.EndCharIndex],
    });
  } else {
    debugger;
    e.vscode.postMessage({
      type: "insertEvent",
      args: [t.Uri, t.StartLine, t.StartCharIndex, t.NewEvent],
    });
  }
}
function onSignificantChange(e) {
  e.vscode.postMessage({
    type: "onSignificantChange",
    args: [{ form: serializeForm(e) }],
  });
}
function IDEOptionsChanged(e) {
  e.showGrid = e.optionGridShow.checked;
  e.alignToGrid = e.optionGridSnap.checked;
  e.showOutlines = e.optionShowOutlines.checked;
  e.alignToGridX = parseInt(e.optionGridWidth.value);
  e.alignToGridY = parseInt(e.optionGridHeight.value);
  if (e.alignToGridX < 1) {
    e.alignToGridX = 1;
    e.optionGridWidth.value = 1;
  }
  if (e.alignToGridY < 1) {
    e.alignToGridY = 1;
    e.optionGridHeight.value = 1;
  }
  if (!e.showGrid) {
    e.menuBarGrid.classList.remove("menuBarToggleOn");
  } else {
    e.menuBarGrid.classList.add("menuBarToggleOn");
  }
  if (e.showOutlines) {
    e.designer.classList.add("designerShowOutlines");
  } else {
    e.designer.classList.remove("designerShowOutlines");
  }
  undoPoint(e);
  document.documentElement.style.setProperty(
    "--gridDimensions",
    e.alignToGridX + "px " + e.alignToGridY + "px"
  );
  getImageFromServer(e, e.designer);
}
function handleDblClickOnControl(e, t) {
  var o;
  if (t.properties.__defaultEvent) {
    o = t.properties.__defaultEvent;
  } else {
    var n = Object.keys(t.properties.__events);
    o = n[n.length - 1];
  }
  if (o) {
    var i = fixupEventInfo(e, t, o);
    if (!i) return;
    jumpToEvent(e, i);
  }
}
function syncIDEOptions(e) {
  e.optionGridShow.checked = e.showGrid;
  e.optionGridSnap.checked = e.alignToGrid;
  e.optionShowOutlines.checked = e.showOutlines;
  e.optionGridWidth.value = e.alignToGridX;
  e.optionGridHeight.value = e.alignToGridY;
  if (!e.showGrid) {
    e.menuBarGrid.classList.remove("menuBarToggleOn");
  } else {
    e.menuBarGrid.classList.add("menuBarToggleOn");
  }
  if (e.showOutlines) {
    e.designer.classList.add("designerShowOutlines");
  } else {
    e.designer.classList.remove("designerShowOutlines");
  }
  document.documentElement.style.setProperty(
    "--gridDimensions",
    e.alignToGridX + "px " + e.alignToGridY + "px"
  );
}
function initUI(e) {
  e.rootElement.oncontextmenu = () => false;
  e.designerContainer.onmousedown = (t) => {
    document_onmousedown(e, t);
  };
  e.designerContainer.onmousemove = (t) => {
    document_onmousemove(e, t);
  };
  e.designerContainer.onmouseout = (t) => {
    document_onmouseout(e, t);
  };
  e.designerContainer.onscroll = () => {
    syncFormDragPoints(e);
    StoreSelectedControlsLastPositions(e);
  };
  e.rootElement.onkeydown = (t) => {
    document_onkeydown(e, t);
  };
  e.rootElement.onkeyup = (t) => {
    document_onkeyup(e, t);
  };
  e.rootElement.oncopy = (t) => {
    document_oncopy(e, t);
  };
  e.rootElement.onpaste = (t) => {
    document_onpaste(e, t, false);
  };
  e.rootElement.onpaste2 = (t) => {
    document_onpaste(e, t, true);
  };
  e.rootElement.oncut = (t) => {
    document_oncut(e, t);
  };
  e.menuBarTest.onclick = () => {
    refreshAllControlImages(e);
  };
  var t = document.createElement("div");
  t.classList = "designerMenuItemAdd";
  t.innerText = "+ 菜单";
  t.onmousedown = () => {
    insertMenuItem(e, e.designer, e.designer.firstChild);
  };
  e.designerMenuBar.appendChild(t, e.designerMenuBar.firstChild);
  e.loadingOverlayIgnoreButton.onclick = () => {
    e.loadingOverlay.classList.add("loadingOverlayHidden");
    e.loadingOverlayInfoBitmapProgress = undefined;
    e.allControls.forEach((e) => {
      if (e.imageData)
        e.style.backgroundImage =
          "url('data:image;base64," + e.imageData + "')";
      e.style.border = "";
    });
    if (e.designer.imageData)
      e.designer.style.backgroundImage =
        "url('data:image;base64," + e.designer.imageData + "')";
  };
  e.menuBarTest.style.visibility = "hidden";
  e.menuBarUndo.onclick = () => {
    ownerUndo(e);
  };
  e.menuBarRedo.onclick = () => {
    ownerRedo(e);
  };
  e.menuBarAlignLeft.onclick = () => alignControlsLeft(e, e.selectedControls);
  e.menuBarAlignLeft.changedSelection = () => {
    if (e.selectedControls.length >= 2) {
      e.menuBarAlignLeft.classList.add("menuBarItemActive");
    } else {
      e.menuBarAlignLeft.classList.remove("menuBarItemActive");
    }
  };
  e.menuBarAlignTop.onclick = () => alignControlsTop(e, e.selectedControls);
  e.menuBarAlignTop.changedSelection = () => {
    if (e.selectedControls.length >= 2) {
      e.menuBarAlignTop.classList.add("menuBarItemActive");
    } else {
      e.menuBarAlignTop.classList.remove("menuBarItemActive");
    }
  };
  e.menuBarAlignRight.onclick = () => alignControlsRight(e, e.selectedControls);
  e.menuBarAlignRight.changedSelection = () => {
    if (e.selectedControls.length >= 2) {
      e.menuBarAlignRight.classList.add("menuBarItemActive");
    } else {
      e.menuBarAlignRight.classList.remove("menuBarItemActive");
    }
  };
  e.menuBarAlignBottom.onclick = () =>
    alignControlsBottom(e, e.selectedControls);
  e.menuBarAlignBottom.changedSelection = () => {
    if (e.selectedControls.length >= 2) {
      e.menuBarAlignBottom.classList.add("menuBarItemActive");
    } else {
      e.menuBarAlignBottom.classList.remove("menuBarItemActive");
    }
  };
  e.menuBarSizeWidest.onclick = () =>
    resizeControlsWidest(e, e.selectedControls);
  e.menuBarSizeWidest.changedSelection = () => {
    if (e.selectedControls.length >= 2) {
      e.menuBarSizeWidest.classList.add("menuBarItemActive");
    } else {
      e.menuBarSizeWidest.classList.remove("menuBarItemActive");
    }
  };
  e.menuBarSizeTallest.onclick = () =>
    resizeControlsTallest(e, e.selectedControls);
  e.menuBarSizeTallest.changedSelection = () => {
    if (e.selectedControls.length >= 2) {
      e.menuBarSizeTallest.classList.add("menuBarItemActive");
    } else {
      e.menuBarSizeTallest.classList.remove("menuBarItemActive");
    }
  };
  e.menuBarSizeNarrowest.onclick = () =>
    resizeControlsNarrowest(e, e.selectedControls);
  e.menuBarSizeNarrowest.changedSelection = () => {
    if (e.selectedControls.length >= 2) {
      e.menuBarSizeNarrowest.classList.add("menuBarItemActive");
    } else {
      e.menuBarSizeNarrowest.classList.remove("menuBarItemActive");
    }
  };
  e.menuBarSizeShortest.onclick = () =>
    resizeControlsShortest(e, e.selectedControls);
  e.menuBarSizeShortest.changedSelection = () => {
    if (e.selectedControls.length >= 2) {
      e.menuBarSizeShortest.classList.add("menuBarItemActive");
    } else {
      e.menuBarSizeShortest.classList.remove("menuBarItemActive");
    }
  };
  e.menuBarGrid.onclick = () => {
    e.showGrid = !e.showGrid;
    syncIDEOptions(e);
    IDEOptionsChanged(e);
  };
  e.menuBarGrid.onmouseenter = () => {
    e.menuBarGridOptions.style.visibility = "visible";
  };
  e.menuBarGrid.onmouseleave = () => {
    e.menuBarGridOptions.style.visibility = "hidden";
  };
  e.menuBarGridOptions.onmouseenter = () => {
    e.menuBarGridOptions.style.visibility = "visible";
  };
  e.menuBarGridOptions.onmouseleave = () => {
    e.menuBarGridOptions.style.visibility = "hidden";
  };
  e.optionGridShow.onchange = () => {
    IDEOptionsChanged(e);
  };
  e.optionGridSnap.onchange = () => {
    IDEOptionsChanged(e);
  };
  e.optionShowOutlines.onchange = () => {
    IDEOptionsChanged(e);
  };
  e.optionGridWidth.onchange = () => {
    IDEOptionsChanged(e);
  };
  e.optionGridHeight.onchange = () => {
    IDEOptionsChanged(e);
  };
  syncIDEOptions(e);
  e.menuBarBringToFront.onclick = () => bringToFront(e);
  e.menuBarBringToFront.changedSelection = () => {
    if (
      e.selectedControls.length >= 1 &&
      e.selectedControls[0] !== e.designer &&
      e.selectedControls[0].properties._className !== "Menu"
    ) {
      e.menuBarBringToFront.classList.add("menuBarItemActive");
    } else {
      e.menuBarBringToFront.classList.remove("menuBarItemActive");
    }
  };
  e.menuBarSendToBack.onclick = () => sendToBack(e);
  e.menuBarSendToBack.changedSelection = () => {
    if (
      e.selectedControls.length >= 1 &&
      e.selectedControls[0] !== e.designer &&
      e.selectedControls[0].properties._className !== "Menu"
    ) {
      e.menuBarSendToBack.classList.add("menuBarItemActive");
    } else {
      e.menuBarSendToBack.classList.remove("menuBarItemActive");
    }
  };
  e.zoomSelect.onchange = () => {
    e.zoomRatio = parseFloat(e.zoomSelect.value);
    e.designerContainer.style.zoom = 100 * e.zoomRatio + "%";
    e.designerMenuBar.style.zoom = 100 * e.zoomRatio + "%";
  };
  e.menuBarPreview.onclick = () => {
    e.vscode.postMessage({
      type: "onClickedPreview",
      args: [{ form: serializeForm(e) }],
    });
  };
  e.controlSelecter.onchange = () => {
    unselectAllControls(e, true);
    e.selectedControls = [
      e.controlSelecter.options[e.controlSelecter.selectedIndex]
        .associatedControl,
    ];
    changedSelectedControls(e);
    StoreSelectedControlsLastPositions(e);
  };
  e.toolbarProperties.onclick = () => {
    e.toolbarProperties.classList.add("selected");
    e.toolbarEvents.classList.remove("selected");
    syncPropertySheet(e);
  };
  e.toolbarEvents.onclick = () => {
    e.toolbarProperties.classList.remove("selected");
    e.toolbarEvents.classList.add("selected");
    syncPropertySheet(e);
  };
  e.formSelectorOption = document.createElement("option");
  e.formSelectorOption.innerHTML = "<b>Unnamed</b>" + " &nbsp;&nbsp;&nbsp;Form";
  e.formSelectorOption.associatedControl = e.designer;
  e.designer.properties = {};
  e.designer.controlSelecterOption = e.formSelectorOption;
  e.controlSelecter.appendChild(e.formSelectorOption);
  e.formSelectorOption.selected = true;
  e.selectedControls = [e.designer];
  changedSelectedControls(e);
  e.designer.isSelected = true;
  e.rootElement.ondblclick = (t) => {
    if (e.selectedTool === e.toolBoxPointer) {
      if (t.target.isMenuControl) {
        handleDblClickOnControl(e, t.target.rootControl);
      } else if (
        t.target.classList.contains("baseControl") ||
        t.target === e.designer
      ) {
        handleDblClickOnControl(e, t.target);
      }
    }
  };
  e.designerDragPointRight.onmousedown = (t) => {
    var o = e.designer.properties.Width;
    e.isDragging = true;
    e.rootElement.onmousemove = (n) => {
      var i = Math.trunc((n.clientX - t.clientX) / e.zoomRatio);
      e.designer.properties.Width = o + i;
      syncUserScaledWidthHeight(e, e.designer);
      syncDesignerControlToProperties(e, e.designer);
      syncFormDragPoints(e);
      syncPropertySheet(e);
      doAnchoringAdjustments(e, e.designer, false);
    };
    e.rootElement.onmouseup2 = (t) => {
      doAnchoringAdjustments(e, e.designer, true);
      if (e.designer.properties.Width != o) {
        undoPoint(e);
        getImageFromServer(e, e.designer);
      }
      e.isDragging = false;
      syncPropertySheet(e);
    };
    e.designerContainer.style.cursor = e.designerDragPointRight.style.cursor;
  };
  e.designerDragPointBottom.onmousedown = (t) => {
    var o = e.designer.properties.Height;
    e.isDragging = true;
    e.rootElement.onmousemove = (n) => {
      var i = Math.trunc((n.clientY - t.clientY) / e.zoomRatio);
      e.designer.properties.Height = o + i;
      syncDesignerControlToProperties(e, e.designer);
      syncFormDragPoints(e);
      syncPropertySheet(e);
      doAnchoringAdjustments(e, e.designer, false);
    };
    e.rootElement.onmouseup2 = (t) => {
      doAnchoringAdjustments(e, e.designer, true);
      if (e.designer.properties.Height != o) {
        undoPoint(e);
        getImageFromServer(e, e.designer);
      }
      e.isDragging = false;
      syncPropertySheet(e);
    };
    e.designerContainer.style.cursor = e.designerDragPointRight.style.cursor;
  };
  e.designerDragPointBottomRight.onmousedown = (t) => {
    var o = e.designer.properties.Width;
    var n = e.designer.properties.Height;
    e.isDragging = true;
    e.rootElement.onmousemove = (i) => {
      var r = Math.trunc((i.clientX - t.clientX) / e.zoomRatio);
      var s = Math.trunc((i.clientY - t.clientY) / e.zoomRatio);
      e.designer.properties.Width = o + r;
      e.designer.properties.Height = n + s;
      syncUserScaledWidthHeight(e, e.designer);
      syncDesignerControlToProperties(e, e.designer);
      syncFormDragPoints(e);
      syncPropertySheet(e);
      doAnchoringAdjustments(e, e.designer, false);
    };
    e.rootElement.onmouseup2 = (t) => {
      doAnchoringAdjustments(e, e.designer, true);
      if (
        e.designer.properties.Width != o ||
        e.designer.properties.Height != n
      ) {
        undoPoint(e);
        getImageFromServer(e, e.designer);
      }
      e.isDragging = false;
      syncPropertySheet(e);
    };
    e.designerContainer.style.cursor = e.designerDragPointRight.style.cursor;
  };
  e.rootElement.onmouseup = (t) => {
    console.log("document_onmouseup");
    e.designerContainer.onmousemove = (t) => {
      document_onmousemove(e, t);
    };
    if (e.propertyValueEditor !== undefined) return;
    if (e.rootElement.onmouseup2) {
      e.rootElement.onmouseup2(e);
      e.rootElement.onmouseup2 = undefined;
    }
    e.rootElement.onmousemove = (e) => {};
    e.designerContainer.style.cursor = "default";
    if (e.selectionArea.style.visibility === "visible") {
      if (e.selectedTool == e.toolBoxPointer) {
        e.selectedControls = [];
        changedSelectedControls(e);
        e.allControls.forEach((t) => {
          if (t.properties._className === "Menu") {
          } else if (!isRectangularControl(e, t)) {
            var o = e.designer.getBoundingClientRect();
            pos1 = {
              left: o.left + t.properties.X1 - 5,
              top: o.top + t.properties.Y1 - 5,
              right: o.left + t.properties.X1 + 5,
              bottom: o.top + t.properties.Y1 + 5,
            };
            pos2 = {
              left: o.left + t.properties.X2 - 5,
              top: o.top + t.properties.Y2 - 5,
              right: o.left + t.properties.X2 + 5,
              bottom: o.top + t.properties.Y2 + 5,
            };
            if (
              doRectanglesIntersect(
                e.selectionArea.getBoundingClientRect(),
                pos1
              ) ||
              doRectanglesIntersect(
                e.selectionArea.getBoundingClientRect(),
                pos2
              )
            ) {
              let o = t.parentNode;
              let n = true;
              while (o != e.designer) {
                if (
                  !doRectanglesIntersect(
                    e.selectionArea.getBoundingClientRect(),
                    o.getBoundingClientRect()
                  )
                ) {
                  n = false;
                  break;
                }
                o = o.parentNode;
              }
              if (n) {
                e.selectedControls.push(t);
                changedSelectedControls(e);
                t.classList.add("baseControlSelected");
                t.isSelected = true;
              }
            }
          } else {
            if (
              doRectanglesIntersect(
                e.selectionArea.getBoundingClientRect(),
                t.getBoundingClientRect()
              )
            ) {
              let o = t.parentNode;
              let n = true;
              while (o != e.designer) {
                if (
                  !doRectanglesIntersect(
                    e.selectionArea.getBoundingClientRect(),
                    o.getBoundingClientRect()
                  )
                ) {
                  n = false;
                  break;
                }
                o = o.parentNode;
              }
              if (n) {
                e.selectedControls.push(t);
                changedSelectedControls(e);
                t.classList.add("baseControlSelected");
                t.isSelected = true;
              }
            }
          }
        });
        if (e.selectedControls.length == 0) {
          e.selectedControls = [e.designer];
          changedSelectedControls(e);
        }
        StoreSelectedControlsLastPositions(e);
        changedSelection(e);
      } else {
        if (
          e.selectionArea.style.width == "0px" &&
          e.selectionArea.style.height == "0px"
        ) {
          e.selectionArea.style.width = "200px";
          e.selectionArea.style.height = "50px";
        }
        var o = e.currentFlashingContainer;
        if (o === e.designerContainer || o === undefined) {
          o = e.designer;
        }
        stopFlashing(e);
        var n = addControl(
          e,
          e.selectedTool.controlType,
          o,
          e.selectedTool.clsid,
          e.selectedTool.controlTypePackage
        );
        n.properties._isNewControl = true;
        n.properties.FontName = e.designer.properties.FontName;
        n.properties.FontSize = e.designer.properties.FontSize;
        n.properties.FontBold = e.designer.properties.FontBold;
        n.properties.FontUnderline = e.designer.properties.FontUnderline;
        n.properties.FontItalic = e.designer.properties.FontItalic;
        n.properties.FontStrikethru = e.designer.properties.FontStrikethru;
        n.isNewlyAddedToContainer = true;
        var i = 0;
        var r = 0;
        var s = o;
        while (s !== e.designerContainer && s !== null) {
          i += s.offsetLeft;
          r += s.offsetTop;
          s = s.parentElement;
        }
        if (e.selectedTool.controlType === "Line") {
          n.properties.X1 = e.selectionArea.XXX_startX - i;
          n.properties.Y1 = e.selectionArea.XXX_startY - r;
          let o = e.designer.getBoundingClientRect();
          o = { left: o.left * e.zoomRatio, top: o.top * e.zoomRatio };
          var a = (t.x - o.left) / e.zoomRatio;
          var l = (t.y - o.top) / e.zoomRatio;
          var d = e.alignToGrid ? a % e.alignToGridX : 0;
          var c = e.alignToGrid ? l % e.alignToGridY : 0;
          n.properties.X2 = a - d - i;
          n.properties.Y2 = l - c - r;
        } else {
          n.properties.Left = parseInt(e.selectionArea.style.left) - i;
          n.properties.Top = parseInt(e.selectionArea.style.top) - r;
          n.properties.Width = e.selectionArea.offsetWidth;
          n.properties.Height = e.selectionArea.offsetHeight;
          syncUserScaledWidthHeight(e, n);
        }
        syncDesignerControlToProperties(e, n);
        e.selectedControls = [n];
        changedSelectedControls(e);
        n.classList.add("baseControlSelected");
        n.isSelected = true;
        StoreSelectedControlsLastPositions(e);
        if (o != e.designer) {
          getImageFromServer(e, o);
        }
        getImageFromServer(e, n);
        undoPoint(e);
      }
    }
    e.selectionArea.style.visibility = "hidden";
    hideDiagonalLine();
    e.designer.classList.remove("noControlPointerEvents");
    e.selectionAreaDragInfoLeft.style.visibility = "hidden";
    e.selectionAreaDragInfoRight.style.visibility = "hidden";
    e.toolBoxPointer.onclick();
    changeToolboxSelectedItem(e);
  };
  e.toolBox.onmouseleave = () => {
    e.toolBox.classList.remove("toolBoxResizeBar");
  };
  e.toolBox.onmousemove = (t) => {
    if (e.toolBox.isResizing || t.offsetX > e.toolBox.offsetWidth - 5) {
      e.toolBox.classList.add("toolBoxResizeBar");
    } else {
      e.toolBox.classList.remove("toolBoxResizeBar");
    }
  };
  e.toolBox.onmousedown = (t) => {
    if (t.offsetX > e.toolBox.offsetWidth - 5) {
      e.toolBox.classList.add("toolBoxResizeBar");
      toolBoxResizer_onmousedown(e, t);
    }
  };
  e.propertiesBox.onmouseleave = () => {
    e.propertiesBox.classList.remove("propertiesBoxResizeBar");
  };
  e.propertiesBox.onmousemove = (t) => {
    if (
      e.propertiesBox.isResizing ||
      (t.offsetX < 5 && t.target === e.propertiesBox)
    ) {
      e.propertiesBox.classList.add("propertiesBoxResizeBar");
    } else {
      e.propertiesBox.classList.remove("propertiesBoxResizeBar");
    }
  };
  e.propertiesBox.onmousedown = (t) => {
    if (t.offsetX < 5 && t.target === e.propertiesBox) {
      e.propertiesBox.classList.add("propertiesBoxResizeBar");
      propertiesBoxResizer_onmousedown(e, t);
    }
  };
  e.rootElement.onmouseleave = e.rootElement.onmouseup;
}
function syncDesignerControlToProperties(e, t, o) {
  var n = t.properties.Width;
  var i = t.properties.Height;
  if (n < 0) {
    n = 0;
    if (o) t.properties.Width = 0;
  }
  if (i < 0) {
    i = 0;
    if (o) t.properties.Height = 0;
  }
  if (t === e.designer) {
    e.designerContainer.style.width = n + "px";
    e.designerContainer.style.height = i + "px";
    e.designerMenuBar.style.width = n + "px";
  } else {
    t.style.left = t.properties.Left + "px";
    t.style.top = t.properties.Top + "px";
    t.style.width = n + "px";
    t.style.height = i + "px";
  }
  t.controlSelecterOption.innerHTML =
    "<b>" +
    t.properties.Name +
    (t.properties.Index === undefined || t.properties.Index === -1
      ? ""
      : "(" + t.properties.Index + ")") +
    "</b> &nbsp;&nbsp;&nbsp;" +
    t.properties._className;
  t.style.filter =
    t.properties.Visible !== false
      ? ""
      : "grayscale(40%) opacity(" +
        (liveIDEOptions["lessTransparentInvisibleControls"] ? 91 : 70) +
        "%)";
  t.style.lineHeight = t.style.height;
  if (
    t.properties._clsid == "{E6E927FA-F6E6-4E8E-9540-DA8696F38429}" ||
    t.properties._isFrame
  ) {
    t.classList.add("baseControlFrame");
  }
}
function sortControlSelecter(e) {
  var t = e.controlSelecter;
  var o = [];
  for (var n = t.options.length - 1; n >= 2; n--)
    o.push(t.removeChild(t.options[n]));
  o.sort(function (e, t) {
    return e.innerText.localeCompare(t.innerText);
  });
  while (o.length) t.appendChild(o.shift());
}
function getBuiltInControlShortNameSpecialCases(e, t) {
  if (e == "VB") {
    if (t === "CommandButton") return "Command";
    if (t === "CheckBox") return "Check";
    if (t === "OptionButton") return "Option";
    if (t === "TextBox") return "Text";
    if (t === "ComboBox") return "Combo";
    if (t === "ListBox") return "List";
    if (t === "HScrollBar") return "HScroll";
    if (t === "VScrollBar") return "VScroll";
    if (t === "DirListBox") return "Dir";
    if (t === "FileListBox") return "File";
    if (t === "DriveListBox") return "Drive";
    if (t === "PictureBox") return "Picture";
  }
  return undefined;
}
function getFirstAvailableStandardControlName(e, t, o) {
  var n = getBuiltInControlShortNameSpecialCases(o, t);
  if (!n) {
    n = t;
  }
  var i = undefined;
  var r = 0;
  while (i !== null) {
    r++;
    i = getControlByName(e, n + r);
  }
  return n + r;
}
function addControl(e, t, o, n, i, r) {
  var s = document.createElement("div");
  s.properties = {};
  s.properties.Name = getFirstAvailableStandardControlName(e, t, i);
  s.properties._clsid = n;
  s.properties._className = t;
  s.id =
    e.FormDesignerInstanceUniqueId.toString() + "_" + e.CustomControlUniqueId++;
  s.classList = "baseControl";
  if (n == "{E6E927FA-F6E6-4E8E-9540-DA8696F38429}") {
    s.classList.add("baseControlFrame");
  }
  let a = o.childNodes.length;
  if (r) {
    o.insertBefore(s, r);
  } else {
    o.appendChild(s);
  }
  s.parentIndex = a;
  s.controlSelecterOption = document.createElement("option");
  s.controlSelecterOption.innerHTML =
    "<b>" +
    s.properties.Name +
    (s.properties.Index === undefined || s.properties.Index === -1
      ? ""
      : "(" + s.properties.Index + ")") +
    "</b> &nbsp;&nbsp;&nbsp;" +
    s.properties._className;
  s.controlSelecterOption.associatedControl = s;
  e.controlSelecter.appendChild(s.controlSelecterOption);
  sortControlSelecter(e);
  if (r) {
    var l = Array.prototype.indexOf.call(e.allControls, r);
    e.allControls.splice(l, 0, s);
  } else {
    e.allControls.push(s);
  }
  return s;
}
function GetMaxTabIndex(e) {
  var t = undefined;
  e.allControls.forEach((e) => {
    if (e.properties) {
      if (e.properties.TabIndex !== undefined) {
        if (t === undefined || e.properties.TabIndex > t) {
          t = e.properties.TabIndex;
        }
      }
    }
  });
  if (t === undefined) t = 0;
  return t;
}
function gotServerMessage(e, t) {
  if (e.loadingOverlayInfoBitmapProgress) {
    e.loadingOverlayInfoBitmapProgress.innerHTML =
      "(" +
      e.totalSerializationRequests +
      " requests, " +
      e.outstandingSerializationRequests +
      " outstanding, " +
      e.totalCountOfOutOfDateRequests +
      " out-of-date)";
  }
  if (e.queuedImageRequests) {
    if (--e.countOfSentServerRequests == 0) {
      flushImageRequestQueue(e);
    }
  }
  var o = new DataView(t.data, 0);
  var n = o.getInt32(0, true);
  var i = getControlById(e, n);
  if (i === null || i === undefined) {
    e.totalCountOfOutOfDateRequests++;
    return;
  }
  i.lastImageRequestId_Received = i.lastImageRequestId;
  var r = o.getInt32(4, true);
  var s = o.getInt32(8, true);
  var a = false;
  var l = false;
  var d = false;
  if (r == -1) {
    r = 0;
    d = true;
  }
  var c = new DataView(t.data, 12 + r, s);
  var u = new TextDecoder().decode(c);
  var p;
  var f;
  var g = false;
  var m = false;
  var h = undefined;
  var v;
  var y;
  var b;
  try {
    p = JSON.parse(u);
    f = p.serialization;
    dynamicChanges = p.dynamicChanges;
    g = p._paintedByParent;
    m = p._isExclusiveWithinContainer;
    h = p.fullTime;
    v = p._twipsX;
    y = p._twipsY;
    b = p._dpi;
    if (!v) debugger;
    if (!y) debugger;
  } catch (e) {
    debugMsg("form designer internal error: unable to parse JSON");
  }
  if (g) {
    i.style.zIndex = i.parentIndex;
  } else {
    i.style.zIndex = i.parentIndex + WINDOWED_CONTROLS_ZINDEX_OFFSET;
  }
  if (d) {
    i.style.backgroundImage = "";
    i.style.backgroundColor = "grey";
    i.style.opacity = 0.7;
    i.style.borderRadius = "5px";
    i.style.fontSize =
      Math.min(i.properties.Width, i.properties.Height) / 2 + "px";
    i.classList.add("baseControlError");
    i.imageData = undefined;
    a = true;
    r = 0;
  } else {
    if (i.isNewlyAddedToContainer) {
      if (i.isNewlyAddedToContainer) {
        if (
          e.designer.properties._clsid ==
          "{33AD5010-6699-11CF-B70C-00AA0060D393}"
        ) {
          if (e.designer.properties.Windowless === true) {
            if (p._paintedByParent || r == 0) {
            } else {
              showModalNotification(
                "错误：无窗口用户控件不能包含窗口的子控件"
              );
              deleteControl(e, i);
              return;
            }
          }
        }
      }
    }
    if (m) {
      f._isExclusiveWithinContainer = true;
    }
    if (v) {
      f.__twipsX = v;
    }
    if (y) {
      f.__twipsX = y;
    }
    f.__dpi = b;
    if (f.ScaleMode === "vbUser") {
      if (f.Width) {
        f.__cachedWidth = f.Width;
        f.__cachedScaledWidthFactor = f.ScaleWidth / f.Width;
      }
      if (f.Height) {
        f.__cachedHeight = f.Height;
        f.__cachedScaledHeightFactor = f.ScaleHeight / f.Height;
      }
    }
    if (g) {
      if (!i.properties._paintedByParent) {
        i.properties._paintedByParent = true;
        getImageFromServer(e, i.parentNode);
      }
      f._paintedByParent = true;
    } else if (r == 0) {
      i.style.backgroundImage = "";
      i.style.backgroundColor = "grey";
      i.style.opacity = 0.7;
      i.style.borderRadius = "5px";
      i.style.fontSize =
        Math.min(i.properties.Width, i.properties.Height) / 2 + "px";
      i.classList.add("baseControlError");
      i.imageData = undefined;
      i.hasFixedSize = true;
      f._isInvisible = true;
      removeSelectedControlDragPoints(e, i);
      l = true;
      e.allToolboxItems.forEach((e) => {
        if (e.clsid == i.properties._clsid) {
          i.style.backgroundImage = e.style.backgroundImage;
          i.classList.remove("baseControlError");
          i.style.opacity = 0.9;
          i.style.borderRadius = "0";
          i.style.backgroundColor = "white";
          i.style.backgroundSize = "calc(100%)";
          i.style.outline = "2px solid #302c2c";
        }
      });
    } else {
      var C = new DataView(t.data, 12, r);
      i.imageData = new TextDecoder().decode(C);
    }
  }
  if (f) {
    if (i.properties) {
      if (i.properties.Left !== undefined) f.Left = i.properties.Left;
      if (i.properties.Top !== undefined) f.Top = i.properties.Top;
    }
  }
  if (f) {
    if (i.properties) {
      if (i.properties.TabIndex === undefined && f.TabIndex === 0) {
        f.TabIndex = GetMaxTabIndex(e) + 1;
      }
      if (f.TabStop === true) {
        i.dataset.tabindex = f.TabIndex;
      } else {
        delete i.dataset.tabindex;
      }
    }
    var E = false;
    if (l) {
      if (i.properties._className === "Menu") {
        i.style.visibility = "hidden";
      } else if (g) {
      } else {
        f.Width = 27;
        f.Height = 27;
        i.style.width = "27px";
        i.style.height = "27px";
        e.allToolboxItems.forEach((e) => {
          if (
            (e.clsid && e.clsid === i.properties._clsid) ||
            e.controlTypePackage + "." + e.controlType ===
              i.properties._className
          ) {
            if (e.toolInfo && e.toolInfo.iconData) {
              i.style.backgroundImage =
                "url('data:image;base64," + e.toolInfo.iconData + "')";
            }
          }
        });
      }
    } else if (
      isRectangularControl(e, i) &&
      (i.properties.Left != f.Left ||
        i.properties.Top != f.Top ||
        i.properties.Width != f.Width ||
        i.properties.Height != f.Height)
    ) {
      E = true;
    }
    i.properties = f;
    i.controlSelecterOption.innerHTML =
      "<b>" +
      i.properties.Name +
      (i.properties.Index === undefined || i.properties.Index === -1
        ? ""
        : "(" + i.properties.Index + ")") +
      "</b> &nbsp;&nbsp;&nbsp;" +
      i.properties._className;
    sortControlSelecter(e);
    if (i.properties._isFrame) {
      i.classList.add("baseControlFrame");
    }
    if (dynamicChanges) {
      dynamicChanges.forEach((t) => {
        var o = getControlByName(e, t.name);
        if (isRectangularControl(e, o)) {
          changeProperty(e, o, "Left", t.left);
          changeProperty(e, o, "Top", t.top);
          changeProperty(e, o, "Width", t.width);
          changeProperty(e, o, "Height", t.height);
        } else {
          changeProperty(e, o, "X1", t.x1);
          changeProperty(e, o, "Y1", t.y1);
          changeProperty(e, o, "X2", t.x2);
          changeProperty(e, o, "Y2", t.y2);
        }
        syncDesignerControlToProperties(e, o);
        getImageFromServer(e, o);
      });
    }
    if (E) {
      syncDesignerControlToProperties(e, i);
      getImageFromServer(e, i);
      if (i.isSelected) showSelectedControlDragPoints(e, i);
      return;
    }
  }
  i.serverErrorInfo = undefined;
  if (l) {
  } else if (!a) {
    i.style.border = "0";
    i.style.borderRadius = 0;
    i.style.opacity = 1;
    i.style.backgroundColor = "";
    if (i === e.designer) {
      i.style.backgroundSize = "cover";
    } else {
      i.style.backgroundSize = "contain";
      if (b != 0 && b != window.devicePixelRatio * 96) {
      }
    }
    i.style.backgroundRepeat = "no-repeat";
    i.classList.remove("baseControlError");
    i.style.opacity = i.properties.Visible == false ? 0.85 : 1;
  } else {
    if (p) {
      if (p.errorInfo) {
        i.serverErrorInfo = p.errorInfo;
        if (i.serverErrorInfo === "!") {
          i.serverErrorInfo = "twinBASIC licence error.";
          showLicenceOverlay(e);
        } else if (
          i.serverErrorInfo.includes(
            "unable to find CustomControl " + formCLSID_Custom
          )
        ) {
          debugMsg(
            e,
            "twinBASIC error: it looks like you haven't added the CustomControls to this project."
          );
        }
      }
    }
  }
  i.lastImageRequestId = undefined;
  e.outstandingSerializationRequests--;
  if (e.loadingOverlayInfoBitmapProgress) {
    e.loadingOverlayInfoBitmapProgress.innerHTML =
      "(" +
      e.totalSerializationRequests +
      " requests, " +
      e.outstandingSerializationRequests +
      " outstanding, " +
      e.totalCountOfOutOfDateRequests +
      " out-of-date)";
  }
  if (e.outstandingSerializationRequests == 0) {
    e.loadingOverlay.classList.add("loadingOverlayHidden");
    e.loadingOverlayInfoBitmapProgress = undefined;
    e.attemptCount = 0;
    e.allControls.forEach((e) => {
      if (e.imageData)
        e.style.backgroundImage =
          "url('data:image;base64," + e.imageData + "')";
      e.style.border = "";
    });
    if (e.designer.imageData)
      e.designer.style.backgroundImage =
        "url('data:image;base64," + e.designer.imageData + "')";
    if (!e.isDragging) {
      var I = performance.now() - e.controlRepaintStart;
      e.vscode.postMessage({
        type: "onChangedNoUndo",
        args: [{ form: serializeForm(e) }],
      });
      if (!i.isInitializing) {
        onSignificantChange(e);
      }
    }
  }
  i.isInitializing = false;
  if (e.selectedControls.includes(i)) {
    syncPropertySheet(e);
  }
  if (e.outstandingSerializationRequests == 0) {
    if (e.afterGotAllImages) {
      let t = e.afterGotAllImages;
      e.afterGotAllImages = undefined;
      t();
    }
  }
}
function isRectangularControl(e, t) {
  if (t.properties === undefined) return true;
  return t.properties.Width !== undefined;
}
function hideAllSubPopupMenus(e, t) {
  if (t) {
    if (t.activeSubMenu) {
      hideAllSubPopupMenus(e, t.activeSubMenu);
      try {
        e.designerContainerOUTER.removeChild(t.activeSubMenu.popupMenu);
      } catch {}
      t.activeSubMenu = undefined;
    }
  }
}
function hideAllPopupMenuDesigners(e) {
  hideAllSubPopupMenus(e, e.designer);
}
function getRelativeOffsets(e, t, o) {
  var n = { left: 0, top: 0 };
  while (t) {
    if (t === o) break;
    n.left += t.offsetLeft;
    n.top += t.offsetTop;
    t = t.parentNode;
  }
  return n;
}
function moveMenuDown(e, t, o) {
  var n = undefined;
  if (t.parentNode === e.designer) {
    var i = t;
    while (i) {
      i = i.previousSibling;
      if (i && i.properties._className === "Menu") {
        break;
      }
    }
    if (i) {
      n = i;
      i.menuControl.parentNode.insertBefore(
        t.menuControl,
        n.menuControl.nextSibling
      );
      hideAllPopupMenuDesigners(e);
      setTimeout(() => {
        o.focus();
      }, 100);
    } else {
      return;
    }
  } else {
    n = o.rootControl.previousSibling;
  }
  let r = t.parentNode;
  r.insertBefore(t, n);
  StoreSelectedControlsLastPositions(e);
  undoPoint(e);
  onSignificantChange(e);
  if (r !== e.designer) showPopupMenuDesigner(e, r);
}
function moveMenuUp(e, t, o) {
  var n;
  if (t.parentNode === e.designer) {
    var i = t;
    while (i) {
      i = i.nextSibling;
      if (i && i.properties._className === "Menu") {
        break;
      }
    }
    if (i) {
      i.menuControl.parentNode.insertBefore(t.menuControl, i.menuControl);
      n = i.nextSibling;
      hideAllPopupMenuDesigners(e);
      setTimeout(() => {
        o.focus();
      }, 100);
    } else {
      return;
    }
  } else if (o.prevMenu) {
    n = o.prevMenu.rootControl.nextSibling;
  } else {
    n = o.rootControl.parentNode.firstChild;
  }
  let r = t.parentNode;
  r.insertBefore(t, n);
  StoreSelectedControlsLastPositions(e);
  undoPoint(e);
  onSignificantChange(e);
  if (r !== e.designer) showPopupMenuDesigner(e, r);
}
function insertMenuBefore(e, t, o) {
  if (t.parentNode === e.designer) {
    debugger;
    var n = t;
    while (n) {
      n = n.nextSibling;
      if (n && n.properties._className === "Menu") {
        break;
      }
    }
    insertMenuItem(e, t.parentNode, n);
  } else {
    insertMenuItem(
      e,
      t.parentNode,
      o.prevMenu ? o.prevMenu.rootControl : undefined
    );
  }
}
function insertMenuAfter(e, t, o) {
  if (t.parentNode === e.designer) {
    var n = t;
    while (n) {
      n = n.previousSibling;
      if (n && n.properties._className === "Menu") {
        break;
      }
    }
    insertMenuItem(e, t.parentNode, n ? n.nextSibling : e.designer.firstChild);
  } else {
    insertMenuItem(e, t.parentNode, t);
  }
}
function deleteMenuItem(e, t, o) {
  hideAllSubPopupMenus(e, t.parentNode);
  e.dontHidePopupMenus = true;
  deleteSelectedControls(e);
  e.dontHidePopupMenus = false;
  undoPoint(e);
  onSignificantChange(e);
  o.parentNode.removeChild(o);
}
function GetSuggesttedNameFromCaption(e, t) {
  t = t.replace(/[^0-9a-z\u0100-\uFFFF]/gi, "");
  return t;
}
function pasteBeforeMenu(e, t, o) {
  if (t.parentNode === e.designer) {
    var n = t;
    while (n) {
      n = n.nextSibling;
      if (n && n.properties._className === "Menu") {
        break;
      }
    }
    pasteMenuItem(e, t.parentNode, n, o);
  } else {
    debugger;
    pasteMenuItem(
      e,
      t.parentNode,
      t.menuControl.prevMenu ? t.menuControl.prevMenu.rootControl : undefined,
      o
    );
  }
}
function pasteIntoMenu(e, t, o) {
  pasteMenuItem(e, t, t, o);
}
function pasteAfterMenu(e, t, o) {
  if (t.parentNode === e.designer) {
    var n = t;
    while (n) {
      n = n.previousSibling;
      if (n && n.properties._className === "Menu") {
        break;
      }
    }
    pasteMenuItem(
      e,
      t.parentNode,
      n ? n.nextSibling : e.designer.firstChild,
      o
    );
  } else {
    pasteMenuItem(e, t.parentNode, t, o);
  }
}
function pasteMenuItem(e, t, o, n) {
  unselectAllControlsPre(e);
  e.selectedControls = deserializeControls(e, n, t, false, false);
  var i = e.selectedControls[0];
  if (i.menuControl) {
    o.menuControl.parentNode.insertBefore(
      i.menuControl,
      o.menuControl.nextSibling
    );
  }
  t.insertBefore(i, o);
  undoPoint(e);
  onSignificantChange(e);
}
function syncMenuItemToLiveControl(e, t, o, n) {
  if (e.IgnoreSyncEvents) return;
  o.isMenuControl = true;
  o.rootControl = t;
  var i = t.properties.Caption;
  i = i.replaceAll("&&", "￪");
  i = i.replaceAll("&", "");
  i = i.replaceAll("￪", "&");
  o.innerText = i;
  o.tabIndex = "0";
  if (t._inlineEdit) {
    var r = document.createElement("input");
    r.value = t.properties.Caption;
    o.innerText = "";
    o.appendChild(r);
    t._inlineEdit = false;
    e.propertyValueEditor = 1;
    var s = r.value;
    r.onRenamed = () => {
      e.IgnoreSyncEvents = true;
      var o = t.properties.Caption;
      changeSelectedControlsProperty(e, "Caption", r.value);
      if (GetSuggesttedNameFromCaption(e, o) === t.properties.Name) {
        var n = GetSuggesttedNameFromCaption(e, r.value);
        if (n.length === 0) n = "Menu";
        var i = getControlByName(e, n);
        if (i !== null && i != t) {
          n = getFirstAvailableStandardControlName(e, n);
        }
        changeSelectedControlsProperty(e, "Name", n);
      }
      e.IgnoreSyncEvents = false;
    };
    r.onkeydown = (n) => {
      if (n.key == "Enter") {
        if (r.value !== t.properties.Caption) {
          r.onRenamed();
        }
        syncMenuItemToLiveControl(e, t, o);
        e.propertyValueEditor = undefined;
      } else if (n.key == "Escape") {
        r.value = s;
        syncMenuItemToLiveControl(e, t, o);
      }
      n.stopPropagation();
    };
    r.onblur = () => {
      if (r.value !== t.properties.Caption) {
        var n = e.selectedControls;
        e.selectedControls = [t];
        r.onRenamed();
        e.selectedControls = n;
      }
      syncMenuItemToLiveControl(e, t, o);
      e.propertyValueEditor = undefined;
    };
    setTimeout(() => {
      r.select();
      r.focus();
    }, 200);
  }
  var a = false;
  var l = false;
  if (t.parentNode === e.designer) {
    o.classList = "designerMenuItem";
    l = true;
  } else {
    if (t.properties.Caption === "-") {
      o.classList = "designerPopUpMenuItemSeperator";
      o.innerText = "";
      a = true;
    } else {
      if (t.children.length > 0) {
        o.classList = "designerPopUpMenuItem designerPopUpMenuItemWithSubItems";
      } else {
        o.classList = "designerPopUpMenuItem";
      }
      if (t.properties.Checked) {
        o.classList.add("designerPopUpMenuItemWithTick");
      }
    }
  }
  if (t.properties.Enabled === false) {
    o.style.color = "#606060";
    o.style.textShadow = "#dedada 1px 1px";
  } else {
    o.style.color = "black";
    o.style.textShadow = "";
  }
  if (t.properties.Visible === false) {
    o.style.opacity = 0.7;
  } else {
    o.style.opacity = 1;
  }
  if (e.selectedControls.length == 1 && t === e.selectedControls[0]) {
    o.classList.add("selectedMenuItem");
    setTimeout(() => {
      o.focus();
    }, 100);
  }
  o.onclick = () => {
    unselectAllControlsPre(e);
    if (t.parentNode === e.designer) {
      unselectAllControls(e);
    }
    e.selectedControls = [t];
    changedSelectedControls(e);
    StoreSelectedControlsLastPositions(e);
    if (!a) {
      showPopupMenuDesigner(e, t);
    } else {
      hideAllSubPopupMenus(e, t.parentNode);
    }
    o.classList.add("selectedMenuItem");
  };
  o.onkeydown = (n) => {
    if (n.key === "F2") {
      t._inlineEdit = true;
      syncMenuItemToLiveControl(e, t, o);
    } else if (!l && n.ctrlKey && n.key === "ArrowDown") {
      moveMenuDown(e, t, o);
    } else if (!l && n.ctrlKey && n.key === "ArrowUp") {
      moveMenuUp(e, t, o);
    } else if (l && n.ctrlKey && n.key === "ArrowLeft") {
      moveMenuUp(e, t, o);
    } else if (l && n.ctrlKey && n.key === "ArrowRight") {
      moveMenuDown(e, t, o);
    } else if (!l && n.key === " ") {
      changeSelectedControlsProperty(
        e,
        "Checked",
        t.properties.Checked ? false : true
      );
    } else if (n.key === "删除") {
      deleteMenuItem(e, t, o);
    }
    n.stopPropagation();
  };
  o.onmousedown = (n) => {
    if (n.button == 2) {
      o.onclick();
      cancelContextMenu(e, n);
      var i;
      e.vscode.postMessage({
        type: "getClipboardData",
        args: ["text/tbControls"],
      });
      e.gotClipboardDataFunction = (r) => {
        var s;
        try {
          s = JSON.parse(r);
        } catch (e) {}
        var a = true;
        if (!Array.isArray(s)) {
          a = false;
        }
        if (a) {
          if (s.length != 1) {
            a = false;
          } else if (s[0]._className !== "Menu") {
            a = false;
          }
        }
        if (l) {
          i = [
            {
              name: "重命名(F2)",
              onclick: () => {
                t._inlineEdit = true;
                syncMenuItemToLiveControl(e, t, o);
              },
            },
            {
              name: "剪切(CTRL+X)",
              onclick: () => {
                e.vscode.postMessage({ type: "cut" });
              },
            },
            {
              name: "复制(CTRL+C)",
              onclick: () => {
                e.vscode.postMessage({ type: "copy" });
              },
            },
            {
              name: "粘贴到前面",
              onclick: () => {
                pasteBeforeMenu(e, t, r);
              },
              isHidden: !a,
            },
            {
              name: "粘贴到后面",
              onclick: () => {
                pasteAfterMenu(e, t, r);
              },
              isHidden: !a,
            },
            {
              name: "粘贴到(CTRL+V)",
              onclick: () => {
                pasteIntoMenu(e, t, r);
              },
              isHidden: !a,
            },
            {},
            {
              name: "左移(CTRL+LEFT)",
              onclick: () => {
                moveMenuUp(e, t, o);
              },
            },
            {
              name: "右移(CTRL+RIGHT)",
              onclick: () => {
                moveMenuDown(e, t, o);
              },
            },
            {},
            {
              name: "切换启用",
              onclick: () => {
                changeSelectedControlsProperty(
                  e,
                  "Enabled",
                  t.properties.Enabled ? false : true
                );
              },
            },
            {
              name: "切换可见",
              onclick: () => {
                changeSelectedControlsProperty(
                  e,
                  "Visible",
                  t.properties.Visible ? false : true
                );
              },
            },
            {},
            {
              name: "插入到前面",
              onclick: () => {
                insertMenuBefore(e, t, o);
              },
            },
            {
              name: "插入到后面",
              onclick: () => {
                insertMenuAfter(e, t, o);
              },
            },
            {},
            {
              name: "删除(DEL)",
              onclick: () => {
                deleteMenuItem(e, t, o);
              },
            },
          ];
        } else {
          i = [
            {
              name: "重命名(F2)",
              onclick: () => {
                t._inlineEdit = true;
                syncMenuItemToLiveControl(e, t, o);
              },
            },
            {
              name: "剪切(CTRL+X)",
              onclick: () => {
                e.vscode.postMessage({ type: "cut" });
              },
            },
            {
              name: "复制(CTRL+C)",
              onclick: () => {
                e.vscode.postMessage({ type: "copy" });
              },
            },
            {
              name: "粘贴到前面",
              onclick: () => {
                pasteBeforeMenu(e, t, r);
              },
              isHidden: !a,
            },
            {
              name: "粘贴到后面",
              onclick: () => {
                pasteAfterMenu(e, t, r);
              },
              isHidden: !a,
            },
            {
              name: "粘贴到(CTRL+V)",
              onclick: () => {
                pasteIntoMenu(e, t, r);
              },
              isHidden: !a,
            },
            {},
            {
              name: "上移(CTRL+UP)",
              onclick: () => {
                moveMenuUp(e, t, o);
              },
            },
            {
              name: "下移(CTRL+DOWN)",
              onclick: () => {
                moveMenuDown(e, t, o);
              },
            },
            {},
            {
              name: "切换选中(SPACE)",
              onclick: () => {
                changeSelectedControlsProperty(
                  e,
                  "Checked",
                  t.properties.Checked ? false : true
                );
              },
            },
            {
              name: "切换启用",
              onclick: () => {
                changeSelectedControlsProperty(
                  e,
                  "Enabled",
                  t.properties.Enabled ? false : true
                );
              },
            },
            {
              name: "切换可见",
              onclick: () => {
                changeSelectedControlsProperty(
                  e,
                  "Visible",
                  t.properties.Visible ? false : true
                );
              },
            },
            {},
            {
              name: "插入到前面",
              onclick: () => {
                insertMenuItem(
                  e,
                  t.parentNode,
                  o.prevMenu ? o.prevMenu.rootControl : null
                );
              },
            },
            {
              name: "插入到后面",
              onclick: () => {
                insertMenuItem(e, t.parentNode, t);
              },
            },
            {},
            {
              name: "插入分隔符到前面",
              onclick: () => {
                insertMenuItem(
                  e,
                  t.parentNode,
                  o.prevMenu ? o.prevMenu.rootControl : null,
                  "-"
                );
              },
            },
            {
              name: "插入分隔符到后面",
              onclick: () => {
                insertMenuItem(e, t.parentNode, t, "-");
              },
            },
            {},
            {
              name: "删除(DEL)",
              onclick: () => {
                deleteMenuItem(e, t, o);
              },
            },
          ];
        }
        showDesignerContextMenu(e, e.contextMenu, n, i);
      };
    }
  };
  if (!n) hideAllSubPopupMenus(e, t.parentNode);
}
function insertMenuItem(e, t, o, n) {
  unselectAllControlsPre(e);
  var i = addControl(
    e,
    "Menu",
    t,
    "{33AD4F68-6699-11CF-B70C-00AA0060D393}",
    "VB",
    o !== undefined ? o : t.firstChild
  );
  i.properties.Caption = n ? n : i.properties.Name;
  i._isNewControl = true;
  if (!n) i._inlineEdit = true;
  i._insertBeforeNode = o;
  syncDesignerControlToProperties(e, i);
  e.selectedControls = [i];
  changedSelectedControls(e);
  i.classList.add("baseControlSelected");
  i.isSelected = true;
  StoreSelectedControlsLastPositions(e);
  undoPoint(e);
  getImageFromServer(e, i);
  onSignificantChange(e);
  if (t !== e.designer) showPopupMenuDesigner(e, t);
}
function showPopupMenuDesigner(e, t) {
  var o = document.createElement("div");
  o.classList = "designerPopUpMenuBar";
  var n = t.menuControl;
  var i = t.parentNode === e.designer;
  hideAllSubPopupMenus(e, t.parentNode);
  var r = getRelativeOffsets(e, n, e.designerContainerOUTER);
  if (i) {
    o.style.left =
      n.offsetLeft * e.zoomRatio +
      e.toolBox.offsetWidth -
      e.designerContainerOUTER.scrollLeft +
      "px";
    o.style.top =
      (n.offsetTop + n.offsetHeight) * e.zoomRatio +
      e.menuBar.offsetHeight -
      e.designerContainerOUTER.scrollTop +
      "px";
  } else {
    o.style.left = r.left + n.offsetWidth + 20 + "px";
    o.style.top = r.top + "px";
  }
  t.popupMenu = o;
  t.parentNode.activeSubMenu = t;
  o.style.visibility = "visible";
  var s = undefined;
  var a = Array.prototype.slice.call(t.children, 0);
  a.forEach((t) => {
    var n = document.createElement("div");
    if (s) s.prevMenu = n;
    syncMenuItemToLiveControl(e, t, n);
    o.insertBefore(n, o.firstChild);
    t.menuControl = n;
    s = n;
  });
  var l = document.createElement("div");
  l.classList = "designerPopUpMenuItemAdd";
  l.innerText = "+";
  l.onmousedown = () => {
    insertMenuItem(e, t);
    syncMenuItemToLiveControl(e, t, t.menuControl, true);
  };
  o.appendChild(l, o.firstChild);
  e.designerContainerOUTER.appendChild(o);
}
var stopAtImageRequest = false;
function getImageFromServer(e, t) {
  if (e.isDragging && t.isSelected && t !== e.designer) {
    t.style.backgroundImage = "";
    t.style.border = "2px solid rgba(40,40,40,0.8)";
    t.style.backgroundColor = "rgba(200,200,200,0.8)";
    t.controlNeedsReimaging = true;
    return;
  }
  if (t.isDeleted) return;
  if (t.properties._paintedByParent) {
    if (!t.isInitializing) {
      getImageFromServer(e, t.parentNode);
    }
  }
  if (t.properties._className === "Menu") {
    t.style.visibility = "hidden";
    if (t.menuControl) {
      syncMenuItemToLiveControl(e, t, t.menuControl);
    } else {
      if (t.parentNode === e.designer) {
        var o = document.createElement("div");
        syncMenuItemToLiveControl(e, t, o);
        t.menuControl = o;
        if (t._isNewControl) {
          debugger;
          e.designerMenuBar.insertBefore(
            o,
            t._insertBeforeNode && t._insertBeforeNode.menuControl
              ? t._insertBeforeNode.menuControl.nextSibling
              : e.designerMenuBar.firstChild
          );
          t.menuControl.classList.add("selectedMenuItem");
        } else {
          e.designerMenuBar.insertBefore(o, e.designerMenuBar.firstChild);
        }
      }
    }
  }
  if (e.outstandingSerializationRequests == 0) {
    e.controlRepaintStart = performance.now();
  }
  e.outstandingSerializationRequests++;
  e.totalSerializationRequests++;
  if (t.lastImageRequestId !== undefined) {
    e.outstandingSerializationRequests--;
    if (t.lastImageRequestId_Received !== t.lastImageRequestId) {
      e.exampleSocket.send(
        e.uniqueFormDesignerId +
          "/" +
          t.lastImageRequestId +
          "/-1/CANCELLATION/0/0"
      );
    }
  }
  if (e.loadingOverlayInfoBitmapProgress) {
    e.loadingOverlayInfoBitmapProgress.innerHTML =
      "(" +
      e.totalSerializationRequests +
      " requests, " +
      e.outstandingSerializationRequests +
      " outstanding, " +
      e.totalCountOfOutOfDateRequests +
      " out-of-date)";
  }
  t.lastImageRequestId = globalShared_ImageRequestId++;
  var n = structuredClone(t.properties);
  {
    if (t.children.length > 0) {
      n.simulatedChildren = [];
      n.windowlessChildren = [];
      var i = Array.prototype.slice.call(t.children, 0);
      i.forEach((t) => {
        if (isRectangularControl(e, t)) {
          n.simulatedChildren.push({
            name: t.properties.Name,
            left: t.properties.Left,
            top: t.properties.Top,
            width: t.properties.Width,
            height: t.properties.Height,
            isNewlyAddedToContainer: t.isNewlyAddedToContainer ? true : false,
          });
        } else {
          n.simulatedChildren.push({
            name: t.properties.Name,
            x1: t.properties.X1,
            y1: t.properties.Y1,
            x2: t.properties.X2,
            y2: t.properties.Y2,
            isNewlyAddedToContainer: t.isNewlyAddedToContainer ? true : false,
          });
        }
        if (t.isNewlyAddedToContainer) t.isNewlyAddedToContainer = false;
        if (t.properties._paintedByParent) {
          n.windowlessChildren.push(t.properties);
        }
      });
    }
  }
  if (t === e.designer) {
    if (e.showGrid) {
      n._gridSizeX = e.alignToGridX;
      n._gridSizeY = e.alignToGridY;
    }
  }
  var r =
    e.uniqueFormDesignerId +
    "/" +
    t.lastImageRequestId +
    "/" +
    window.devicePixelRatio * 1e6 +
    "/" +
    e.designer.properties.FormDesignerId +
    "/" +
    (t === e.designer ? 1 : 0) +
    "/" +
    JSON.stringify(n, replacer);
  if (e.queuedImageRequests) {
    e.queuedImageRequests.push(r);
  } else {
    e.exampleSocket.send(r);
  }
  if (t === e.designer) {
  } else {
    if (!e.DisableControlsRepaintBoxes) {
      t.style.backgroundImage = "";
      t.style.border = "2px solid rgba(40,40,40,0.8)";
      t.style.backgroundColor = "rgba(200,200,200,0.8)";
    }
    t.style.borderRadius = 0;
    t.style.opacity = 1;
    t.style.backgroundSize = "contain";
    t.style.backgroundRepeat = "no-repeat";
    t.classList.remove("baseControlError");
  }
}
function doRectanglesIntersect(e, t) {
  const o = (e) => Math.max(e.x1, e.x2);
  const n = (e) => Math.max(e.y1, e.y2);
  const i = (e) => Math.min(e.x1, e.x2);
  const r = (e) => Math.min(e.y1, e.y2);
  const s = { x1: e.left, y1: e.top, x2: e.right, y2: e.bottom };
  const a = { x1: t.left, y1: t.top, x2: t.right, y2: t.bottom };
  const l = o(s) <= i(a) || i(s) >= o(a);
  const d = n(s) <= r(a) || r(s) >= n(a);
  return !(l || d);
}
function refreshUI(e) {}
function debugMsg(e, t) {
  e.vscode.postMessage({ type: "debugMsg", args: [t] });
}
function debugMsg2(e, t) {
  e.vscode.postMessage({ type: "debugMsg2", args: [t] });
}
function debugModalQuestion(e, t, o, n) {
  e.vscode.postMessage({ type: "debugModalQuestion", args: [t, o, n] });
}
function serializeSelection(e) {
  var t = [];
  e.selectedControls.forEach((e) => {
    t.push(e.properties.Name);
  });
  return t;
}
function deserializeSelection(e, t) {
  e.selectedControls = [];
  changedSelectedControls(e);
  if (t) {
    t.forEach((t) => {
      e.allControls.forEach((o) => {
        if (t === o.properties.Name) {
          e.selectedControls.push(o);
        }
      });
    });
  }
  if (e.selectedControls.length == 0) {
    e.selectedControls = [e.designer];
    changedSelectedControls(e);
  }
  StoreSelectedControlsLastPositions(e);
}
function ownerUndo(e) {
  e.vscode.postMessage({ type: "ownerUndo" });
}
function ownerRedo(e) {
  e.vscode.postMessage({ type: "ownerRedo" });
}
function undoPoint(e) {
  setUndoRedoButtonsState(e, true, false);
  e.vscode.postMessage({
    type: "onChanged",
    args: [{ selected: serializeSelection(e), form: serializeForm(e) }],
  });
}
function changedSelection(e) {
  e.vscode.postMessage({
    type: "onChangedSelection",
    args: [serializeSelection(e)],
  });
}
function setUndoRedoButtonsState(e, t, o) {
  e.menuBarUndo.classList.remove("menuBarItemActive");
  if (t) {
    e.menuBarUndo.classList.add("menuBarItemActive");
  }
  e.menuBarRedo.classList.remove("menuBarItemActive");
  if (o) {
    e.menuBarRedo.classList.add("menuBarItemActive");
  }
}
function isObject(e) {
  return typeof e === "object" && e !== null && !Array.isArray(e);
}
function setupPropertyEditor2_Exception(e, t, o, n, i) {
  t.innerText = "⚠ " + n;
  t.classList.add("errorPropertySheet");
}
function setupPropertyEditor2_Unsupported(e, t, o, n, i) {
  if (n === null) {
    if (Array.isArray(i)) {
      t.innerHTML =
        "<span class='treeObject'> ... { empty array of " + i[0] + "}</span>";
    } else {
      t.innerHTML =
        "<span class='treeObject'> ... { Nothing " +
        (i !== undefined ? " / " + i : "") +
        "}</span>";
    }
  } else {
    t.innerHTML = n;
  }
}
function resetExclusiveValuesInContainer(e, t, o) {
  var n = t.childNodes.length;
  var i = 0;
  while (i < n) {
    var r = t.childNodes[i++];
    if (r.properties._isExclusiveWithinContainer) {
      if (r !== o) {
        if (r.properties.Value) {
          changeProperty(e, r, "Value", false);
          getImageFromServer(e, r);
        }
      }
    }
  }
}
function changeProperty(e, t, o, n, i) {
  var r = false;
  var s = t.properties;
  if (o === "Name") {
    var a = getControlByName(e, n);
    if (a === null) {
      var l = unlockTheControl(e, s.Name, true);
      if (l) lockTheControl(e, n, true);
    } else if (a.properties === s) {
      if (a.properties.Name === n) {
        return;
      } else {
      }
    } else {
      if (a.properties.Index === undefined) {
        debugMsg("error: a control already exists with the name '" + n + "'");
      } else if (a.properties.Index == -1) {
        debugModalQuestion(
          e,
          "A control already exists with the name '" +
            n +
            "'. \n\nDo you want to create a control array?",
          () => {
            changeProperty(e, a, "Index", 0);
            getImageFromServer(e, a);
            changeProperty(e, t, "Name", n);
          }
        );
        return;
      } else {
        t.properties.Index = getControlArrayMaxIndex(e, n) + 1;
        r = true;
      }
    }
  } else if (o === "Index") {
    if (
      n === undefined ||
      n === null ||
      Number.isNaN(n) ||
      n < -1 ||
      n > 32767
    ) {
      n = -1;
    }
  } else if (o === "Value") {
    if (s._isExclusiveWithinContainer && n) {
      resetExclusiveValuesInContainer(e, t.parentNode, t);
    }
  } else if (
    o === "ScaleLeft" ||
    o === "ScaleTop" ||
    o === "ScaleWidth" ||
    o === "ScaleHeight"
  ) {
    s.ScaleMode = "vbUser";
  } else if (o === "WhatsThisButton") {
    if (n === true) {
      changeProperty(e, t, "MinButton", false);
      changeProperty(e, t, "MaxButton", false);
      changeProperty(e, t, "ControlBox", true);
    }
  } else if (o === "ControlContainer") {
    if (s._clsid == "{33AD5010-6699-11CF-B70C-00AA0060D393}") {
      if (s.Windowless) {
        showModalNotification(
          "ERROR: A Windowless control cannot also be a container"
        );
        return;
      }
    }
  } else if (o === "EditAtDesignTime") {
    if (s._clsid == "{33AD5010-6699-11CF-B70C-00AA0060D393}") {
      if (s.Windowless) {
        showModalNotification(
          "ERROR: A Windowless control cannot also have the EditAtDesignTime property set"
        );
        return;
      }
    }
  } else if (o === "Windowless") {
    if (s._clsid == "{33AD5010-6699-11CF-B70C-00AA0060D393}") {
      if (n === true) {
        var d = t.childNodes.length;
        var c = 0;
        while (c < d) {
          var u = t.childNodes[c++];
          if (u.properties._paintedByParent || u.properties._isInvisible) {
          } else {
            showModalNotification(
              "错误：无窗口用户控件不能包含窗口的子控件"
            );
            return;
          }
        }
      }
      if (s.ControlContainer) {
        showModalNotification(
          "ERROR: A container control cannot also be Windowless"
        );
        return;
      }
      if (s.EditAtDesignTime) {
        showModalNotification(
          "ERROR: EditAtDesignTime is not supported for Windowless controls"
        );
        return;
      }
    }
  }
  if (Number.isNaN(n)) {
    n = 0;
  }
  let p = o.split(".");
  let f = p.pop();
  p.forEach((e) => {
    let t = e.indexOf("(");
    if (t != -1) {
      let o = e.substring(t + 1);
      o = o.substring(0, o.length - 1);
      e = e.substring(0, t);
      s = s[e][o];
    } else {
      s = s[e];
    }
  });
  let g = f.indexOf("(");
  if (g != -1) {
    let e = f.substring(g + 1);
    e = e.substring(0, e.length - 1);
    f = f.substring(0, g);
    if (e === "+") {
      if (s[f] === null) {
        s[f] = [];
      }
      s[f].push(n);
    } else if (e.substring(0, 1) === "+") {
      var m = parseInt(e.substring(1));
      if (s[f] === null) {
        s[f] = [];
      }
      s[f].splice(m, 0, n);
    } else if (n === undefined) {
      s[f].splice(parseInt(e), 1);
    } else {
      s[f][e] = n;
    }
  } else {
    s[f] = n;
    s["_propertyChanged_" + f] = true;
    if (i) s["_propertyChangedWasIPPB_" + f] = true;
  }
  if (o === "Name") onSignificantChange(e);
  if (r) getImageFromServer(e, t);
}
function replacer(e, t) {
  if (e.substring(0, 2) === "__") {
    return undefined;
  }
  return t;
}
function changeSelectedControlsProperty(e, t, o, n) {
  e.restorePropertiesBoxScroll = e.propertiesBoxInner.scrollTop;
  var i = t == "Left" || t == "Top";
  var r = t == "Width" || t == "Height";
  e.selectedControls.forEach((s) => {
    changeProperty(e, s, t, o, n);
    if (!i || s.properties.Dock === e.tbDockNone) {
      syncDesignerControlToProperties(e, s);
      if (
        t === "Dock" ||
        (r &&
          s.properties.Dock !== undefined &&
          s.properties.Dock !== e.tbDockNone)
      ) {
        doAnchoringAdjustments(e, s.parentElement, true);
      }
    }
  });
  StoreSelectedControlsLastPositions(e);
  undoPoint(e);
  e.selectedControls.forEach((t) => {
    getImageFromServer(e, t);
  });
}
function propertyOnGotFocus(e, t, o) {
  e.propertyValueEditor = 1;
  e.proprtiesBoxFooter.innerText = t.title;
  if (e.proprtiesBoxFooter.innerHTML)
    e.proprtiesBoxFooter.innerHTML =
      e.infoIcon + e.proprtiesBoxFooter.innerHTML;
  e.focusedPropertyName = o;
}
function propertyOnLostFocus(e) {
  e.propertyValueEditor = undefined;
  e.proprtiesBoxFooter.innerText = "";
}
function setupPropertyEditor2_String(e, t, o, n, i, r) {
  var s = document.createElement("input");
  s.type = "text";
  if (n !== null) s.value = n;
  s.onchange = () => {
    changeSelectedControlsProperty(e, o, s.value);
  };
  s.onfocus = () => {
    propertyOnGotFocus(e, t, o);
  };
  s.onblur = () => {
    propertyOnLostFocus(e, t, o);
  };
  t.appendChild(s);
  r.ondblclick = () => {
    s.focus();
    s.select();
  };
}
function setupPropertyEditor2_Boolean(e, t, o, n, i, r) {
  var s = document.createElement("input");
  s.type = "checkbox";
  s.checked = n;
  s.indeterminate = n === null;
  s.onchange = () => {
    changeSelectedControlsProperty(e, o, s.checked);
  };
  s.onfocus = () => {
    propertyOnGotFocus(e, t, o);
  };
  s.onblur = () => {
    propertyOnLostFocus(e, t, o);
  };
  t.appendChild(s);
  r.ondblclick = () => {
    s.checked = !s.checked;
    changeSelectedControlsProperty(e, o, s.checked);
  };
  if (!s.indeterminate) {
    var a = document.createElement("div");
    a.className = "propertyValueBoolText";
    a.innerHTML = n === true ? "True" : "False";
    t.appendChild(a);
    t.ondblclick = () => {
      changeSelectedControlsProperty(e, o, !s.checked);
    };
  }
}
function setupPropertyEditor2_Integer(e, t, o, n, i, r) {
  var s = document.createElement("input");
  s.type = "number";
  if (n !== null) s.value = n;
  s.onchange = () => {
    changeSelectedControlsProperty(e, o, parseInt(s.value));
  };
  s.onfocus = () => {
    propertyOnGotFocus(e, t, o);
  };
  s.onblur = () => {
    propertyOnLostFocus(e, t, o);
  };
  t.appendChild(s);
  r.ondblclick = () => {
    s.focus();
    s.select();
  };
}
function setupPropertyEditor2_Long(e, t, o, n, i, r, s, a, l) {
  if (o === "Index") {
    if (n === -1) n = "";
  }
  if (s) {
    n *= s;
  }
  if (a) {
    n += a;
  }
  var d = document.createElement("input");
  d.type = "number";
  if (n !== null) d.value = n;
  d.onchange = () => {
    if (o == "Left") {
      StoreSelectedControlsLastPositions(e);
      syncFormDragPoints(e);
    }
    var t = parseInt(d.value);
    if (a) {
      t -= a;
    }
    if (s) {
      t /= s;
    }
    changeSelectedControlsProperty(e, o, t);
  };
  d.onfocus = () => {
    propertyOnGotFocus(e, t, o);
  };
  d.onblur = () => {
    propertyOnLostFocus(e, t, o);
  };
  t.appendChild(d);
  if (l) {
    var c = document.createElement("div");
    c.className = "unitText";
    c.innerText = l;
    t.appendChild(c);
  }
  r.ondblclick = () => {
    d.focus();
    d.select();
  };
}
function setupPropertyEditor2_Single(e, t, o, n, i, r) {
  var s = document.createElement("input");
  s.type = "number";
  if (n !== null) s.value = n;
  s.onchange = () => {
    changeSelectedControlsProperty(e, o, parseFloat(s.value));
  };
  s.onfocus = () => {
    propertyOnGotFocus(e, t, o);
  };
  s.onblur = () => {
    propertyOnLostFocus(e, t, o);
  };
  t.appendChild(s);
  r.ondblclick = () => {
    s.focus();
    s.select();
  };
}
function setupPropertyEditor2_Double(e, t, o, n, i, r) {
  var s = document.createElement("input");
  s.type = "number";
  if (n !== null) s.value = n;
  s.onchange = () => {
    changeSelectedControlsProperty(e, o, parseFloat(s.value));
  };
  s.onfocus = () => {
    propertyOnGotFocus(e, t, o);
  };
  s.onblur = () => {
    propertyOnLostFocus(e, t, o);
  };
  t.appendChild(s);
  r.ondblclick = () => {
    s.focus();
    s.select();
  };
}
function setupPropertyEditor2_Currency(e, t, o, n, i, r) {
  var s = document.createElement("input");
  s.type = "number";
  if (n !== null) s.value = n;
  s.onchange = () => {
    changeSelectedControlsProperty(e, o, parseFloat(s.value));
  };
  s.onfocus = () => {
    propertyOnGotFocus(e, t, o);
  };
  s.onblur = () => {
    propertyOnLostFocus(e, t, o);
  };
  t.appendChild(s);
  r.ondblclick = () => {
    s.focus();
    s.select();
  };
}
function setupPropertyEditor2_Date(e, t, o, n, i, r) {
  var s = document.createElement("input");
  s.type = "number";
  if (n !== null) s.value = n;
  s.onchange = () => {
    changeSelectedControlsProperty(e, o, parseFloat(s.value));
  };
  s.onfocus = () => {
    propertyOnGotFocus(e, t, o);
  };
  s.onblur = () => {
    propertyOnLostFocus(e, t, o);
  };
  t.appendChild(s);
  r.ondblclick = () => {
    s.focus();
    s.select();
  };
}
function setupPropertyEditor2_Decimal(e, t, o, n, i, r) {
  var s = document.createElement("input");
  s.type = "number";
  if (n !== null) s.value = n;
  s.onchange = () => {
    changeSelectedControlsProperty(e, o, parseFloat(s.value));
  };
  s.onfocus = () => {
    propertyOnGotFocus(e, t, o);
  };
  s.onblur = () => {
    propertyOnLostFocus(e, t, o);
  };
  t.appendChild(s);
  r.ondblclick = () => {
    s.focus();
    s.select();
  };
}
function setupPropertyEditor2_Byte(e, t, o, n, i, r) {
  var s = document.createElement("input");
  s.type = "number";
  if (n !== null) s.value = n;
  s.onchange = () => {
    changeSelectedControlsProperty(e, o, parseInt(s.value));
  };
  s.onfocus = () => {
    propertyOnGotFocus(e, t, o);
  };
  s.onblur = () => {
    propertyOnLostFocus(e, t, o);
  };
  t.appendChild(s);
  r.ondblclick = () => {
    s.focus();
    s.select();
  };
}
function setupPropertyEditor2_LongLong(e, t, o, n, i, r) {
  var s = document.createElement("input");
  s.type = "number";
  if (n !== null) s.value = n;
  s.onchange = () => {
    changeSelectedControlsProperty(e, o, parseInt(s.value));
  };
  s.onfocus = () => {
    propertyOnGotFocus(e, t, o);
  };
  s.onblur = () => {
    propertyOnLostFocus(e, t, o);
  };
  t.appendChild(s);
  r.ondblclick = () => {
    s.focus();
    s.select();
  };
}
function setupPropertyEditor2_Enumeration(e, t, o, n, i, r, s) {
  var a = document.createElement("select");
  var l = false;
  i.forEach((e) => {
    if (e !== "vbContainerPosition" && e != "vbContainerSize") {
      var t = document.createElement("option");
      t.innerHTML = e;
      t.internalValue = e;
      if (e == n) {
        l = true;
        t.selected = true;
      }
      a.insertBefore(t, a.firstChild);
    }
  });
  if (!l) {
    var d = document.createElement("option");
    if (n !== null) {
      d.innerHTML = n;
      d.internalValue = n;
    }
    d.selected = true;
    d.hidden = true;
    a.insertBefore(d, a.firstChild);
  }
  a.onchange = () => {
    changeSelectedControlsProperty(e, o, a.value, s);
  };
  a.onfocus = () => {
    propertyOnGotFocus(e, t, o);
  };
  a.onblur = () => {
    propertyOnLostFocus(e, t, o);
  };
  if (r)
    r.ondblclick = () => {
      if (a.selectedIndex == a.length - 1) {
        a.selectedIndex = 0;
      } else {
        a.selectedIndex += 1;
      }
      changeSelectedControlsProperty(e, o, a.value, s);
    };
  a.size = 1;
  t.appendChild(a);
}
function designer_PictureBytes() {
  this.render = (e, t, o) => {
    var n = this.globals;
    var i = document.createElement("div");
    var r = o ? (o.length / 4) * 3 : 0;
    if (o && o.slice(o.length - 1) == "=") {
      r--;
      if (o.slice(o.length - 2) == "==") {
        r--;
      }
    }
    i.innerHTML = "{" + r + " bytes}";
    e.appendChild(i);
    if (r > 0) {
      var s = document.createElement("div");
      s.classList = "propertyValueRedX";
      s.innerHTML = "X";
      s.onclick = (e) => {
        changeSelectedControlsProperty(n, t, "");
        e.stopPropagation();
      };
      e.appendChild(s);
    }
  };
  this.ellipsesClick = (e, t, o) => {
    this.globals.vscode.postMessage({
      type: "openFilePictureBytes",
      args: [t],
    });
  };
}
function designer_PictureBytesLen() {
  this.render = (e, t, o) => {
    var n = this.globals;
    var i = document.createElement("div");
    var r = o;
    i.innerHTML = "{" + r + " bytes}";
    e.appendChild(i);
    if (r > 0) {
      var s = document.createElement("div");
      s.classList = "propertyValueRedX";
      s.innerHTML = "X";
      s.onclick = (e) => {
        changeSelectedControlsProperty(n, t, "");
        e.stopPropagation();
      };
      e.appendChild(s);
    }
  };
  this.ellipsesClick = (e, t, o) => {
    this.globals.vscode.postMessage({
      type: "openFilePictureBytes",
      args: [t],
    });
  };
}
function designer_IconBytes() {
  this.render = (e, t, o) => {
    var n = this.globals;
    var i = document.createElement("div");
    var r = o ? (o.length / 4) * 3 : 0;
    if (o && o.slice(o.length - 1) == "=") {
      r--;
      if (o.slice(o.length - 2) == "==") {
        r--;
      }
    }
    i.innerHTML = "{" + r + " bytes}";
    e.appendChild(i);
    if (r > 0) {
      var s = document.createElement("div");
      s.classList = "propertyValueRedX";
      s.innerHTML = "X";
      s.onclick = (e) => {
        changeSelectedControlsProperty(n, t, "");
        e.stopPropagation();
      };
      e.appendChild(s);
    }
  };
  this.ellipsesClick = (e, t, o) => {
    this.globals.vscode.postMessage({ type: "openFileIconBytes", args: [t] });
  };
}
function designer_Spectrum() {
  this.render = (e, t, o) => {
    var n = this.globals;
    var i = document.createElement("div");
    i.className = "colorElement";
    var r = (o >> 24) & 255;
    var s = (o >> 16) & 255;
    var a = (o >> 8) & 255;
    var l = (o >> 0) & 255;
    var d = "#" + byteToHex(r) + byteToHex(l) + byteToHex(a) + byteToHex(s);
    i.style.background = "rgba(" + l + "," + a + "," + s + "," + r / 255 + ")";
    e.appendChild(i);
    var c = document.createElement("div");
    c.className = "colorElementText";
    var u =
      byteToHex(r).toUpperCase() +
      byteToHex(s).toUpperCase() +
      byteToHex(a).toUpperCase() +
      byteToHex(l).toUpperCase();
    c.innerHTML = "&H";
    var p = document.createElement("input");
    p.type = "text";
    p.className = "colorElementTextInput";
    p.value = u;
    p.onchange = () => {
      var e = parseInt(Number("0x" + p.value), 10);
      if (e > 2147483647) {
        e = -(~e + 1);
      }
      changeSelectedControlsProperty(n, t, e);
    };
    p.onfocus = () => {
      n.propertyValueEditor = 1;
    };
    p.onblur = () => {
      n.propertyValueEditor = undefined;
    };
    c.appendChild(p);
    var f = document.createElement("div");
    f.innerHTML = " (ABGR)";
    f.className = "colorElementABGRHint";
    c.appendChild(f);
    e.appendChild(c);
    var g = document.createElement("input");
    g.type = "text";
    g.className = "colorPicker_hidden";
    g.change = (o) => {
      if (g.colorPickerVisible) {
        $(g).spectrum("destroy");
        e.removeChild(g);
      }
      g.colorPickerVisible = false;
      n.windowsPalette = window.localStorage["twinbasic.formColors"];
      saveFormDesignerEditorConfiguration(n);
      if (g.value === "") {
        g.value = d;
      } else {
        var i = parseInt(g.value.substring(1), 16);
        if (i > 2147483647) {
          i = -(~i + 1);
        }
        var r = (i >> 24) & 255;
        var s = (i >> 16) & 255;
        var a = (i >> 8) & 255;
        var l = (i >> 0) & 255;
        changeSelectedControlsProperty(
          n,
          t,
          (r << 24) | (l << 16) | (a << 8) | s
        );
      }
    };
    if (!n.isDragging) {
    }
    i.onclick = () => {
      setTimeout(() => {
        e.appendChild(g);
        $(g).spectrum({
          preferredFormat: "hex8",
          localStorageKey: "twinbasic.formColors",
          showButtons: true,
          selectionPalette: n.windowsPalette.split(";"),
          maxSelectionSize: 7,
        });
        $(g).spectrum("set", d);
        g.value = d;
        $(g).spectrum("show");
        var t = $(g).spectrum("container");
        var o = t[0].getBoundingClientRect();
        var i = e.getBoundingClientRect();
        var r = document.getElementById("root").getBoundingClientRect();
        var s = i.left;
        var a = o.right - o.left;
        if (s + a > r.right) {
          s = r.right - a;
        }
        t[0].style.left = s + "px";
        t[0].style.top = i.top + 20 + "px";
        g.colorPickerVisible = true;
      }, 0);
      return false;
    };
    this.otherDoubleClick = () => {
      i.onclick();
    };
  };
}
function designer_SpectrumWindowsOrClear() {
  this.render = (e, t, o, n) => {
    var i = new designer_SpectrumWindows();
    i.globals = this.globals;
    i.minus1IsClear = true;
    i.render(e, t, o, n);
  };
}
function designer_SpectrumWindows() {
  this.render = (e, t, o, n) => {
    var i = this.globals;
    var r = (o >> 24) & 255;
    var s = (o >> 16) & 255;
    var a = (o >> 8) & 255;
    var l = (o >> 0) & 255;
    var d =
      byteToHex(s).toUpperCase() +
      byteToHex(a).toUpperCase() +
      byteToHex(l).toUpperCase();
    if (r != 0) d = byteToHex(r).toUpperCase() + d;
    if (n === undefined) n = o;
    var c = document.createElement("div");
    c.className = "colorElement";
    r = (n >> 24) & 255;
    s = (n >> 16) & 255;
    a = (n >> 8) & 255;
    l = (n >> 0) & 255;
    c.style.background = "rgb(" + l + "," + a + "," + s + ")";
    e.appendChild(c);
    var u = "#" + byteToHex(l) + byteToHex(a) + byteToHex(s);
    var p = document.createElement("div");
    p.className = "colorElementText";
    p.innerHTML = "&H";
    var f = document.createElement("input");
    f.type = "text";
    f.className = "colorElementTextInput";
    f.value = d;
    if (this.minus1IsClear) {
      if (o === -1) {
        p.innerHTML = "";
        f.value = "(not set)";
      }
    }
    f.onchange = () => {
      if (f.value === "" && this.minus1IsClear) f.value = "FFFFFFFF";
      var e = parseInt(Number("0x" + f.value), 10);
      if (e > 2147483647) {
        e = -(~e + 1);
      }
      changeSelectedControlsProperty(i, t, e);
    };
    f.onfocus = () => {
      i.propertyValueEditor = 1;
    };
    f.onblur = () => {
      i.propertyValueEditor = undefined;
    };
    p.appendChild(f);
    var g = document.createElement("div");
    g.innerHTML = " (BGR)";
    g.className = "colorElementABGRHint";
    p.appendChild(g);
    e.appendChild(p);
    var m = document.createElement("input");
    m.type = "text";
    m.className = "colorPicker_hidden";
    m.change = (o) => {
      if (m.colorPickerVisible) {
        $(m).spectrum("destroy");
        e.removeChild(m);
      }
      m.colorPickerVisible = false;
      i.windowsPalette = window.localStorage["twinbasic.formColors"];
      saveFormDesignerEditorConfiguration(i);
      if (m.value === "") {
        m.value = u;
      } else {
        var n = parseInt(m.value.substring(1), 16);
        if (n > 2147483647) {
          n = -(~n + 1);
        }
        var r = (n >> 16) & 255;
        var s = (n >> 8) & 255;
        var a = (n >> 0) & 255;
        changeSelectedControlsProperty(i, t, (a << 16) | (s << 8) | r);
      }
    };
    if (!i.isDragging) {
    }
    c.onclick = () => {
      setTimeout(() => {
        e.appendChild(m);
        $(m).spectrum({
          preferredFormat: "hex",
          localStorageKey: "twinbasic.formColors",
          showButtons: true,
          showAlpha: false,
          selectionPalette: i.windowsPalette.split(";"),
          maxSelectionSize: 7,
        });
        $(m).spectrum("set", u);
        $(m).spectrum("show");
        var t = $(m).spectrum("container");
        var o = t[0].getBoundingClientRect();
        var n = e.getBoundingClientRect();
        var r = document.getElementById("root").getBoundingClientRect();
        var s = n.left;
        var a = o.right - o.left;
        if (s + a > r.right) {
          s = r.right - a;
        }
        t[0].style.left = s + "px";
        t[0].style.top = n.top + 20 + "px";
        m.colorPickerVisible = true;
      }, 0);
      return false;
    };
    this.otherDoubleClick = () => {
      c.onclick();
    };
  };
}
function designer_Grapick() {
  this.ellipsesClick = (e, t, o) => {
    var n = e.getBoundingClientRect();
    CustomDesigner_Grapick_OnClick(this.globals, n.left, n.top, t, o);
  };
}
function designer_Event() {
  this.preRender = (e, t, o) => {
    e.style.cursor = "pointer";
  };
  this.ellipsesClick = (e, t, o) => {
    var n = this.globals.selectedControls[0].properties.__events[t];
    jumpToEvent(this.globals, n);
  };
}
function designer_PropertyPage() {
  this.render = (e, t, o, n) => {
    var i = document.createElement("div");
    i.innerText = "{ PropertyPage }";
    i.className = "propertyPage";
    e.appendChild(i);
  };
  this.preRender = (e, t, o) => {
    e.style.cursor = "pointer";
  };
  this.ellipsesClick = (e, t, o) => {
    if (this.globals.outstandingSerializationRequests) {
      msgBox(
        "后端编译器似乎繁忙。  检查IDE窗口背后的对话框是否打开。"
      );
      return;
    }
    t = t.substr(1, t.length - 2);
    changeSelectedControlsProperty(this.globals, "_openPropertyPage", t);
  };
}
function designer_FontList() {
  this.render = (e, t, o, n) => {
    setupPropertyEditor2_Enumeration(
      this.globals,
      e,
      t,
      o,
      GlobalFontsList,
      undefined
    );
  };
}
function designer_RestrictedOLEDropMode() {
  this.render = (e, t, o, n) => {
    setupPropertyEditor2_Enumeration(
      this.globals,
      e,
      t,
      o,
      ["vbOLEDropNone", "vbOLEDropManual"],
      undefined
    );
  };
}
function designer_scaleMode_vbTwips() {
  this.render = (e, t, o, n, i, r, s) => {
    setupPropertyEditor2_Long(
      this.globals,
      e,
      t,
      o,
      undefined,
      i,
      r,
      s,
      "twips"
    );
  };
}
function designer_scaleMode_vbPixels() {
  this.render = (e, t, o, n, i, r, s) => {
    setupPropertyEditor2_Long(
      this.globals,
      e,
      t,
      o,
      undefined,
      i,
      r,
      s,
      "pixels"
    );
  };
}
function designer_scaleMode_vbUser() {
  this.render = (e, t, o, n, i, r, s) => {
    setupPropertyEditor2_Long(
      this.globals,
      e,
      t,
      o,
      undefined,
      i,
      r,
      s,
      "units"
    );
  };
}
function designer_scaleMode_vbPoints() {
  this.render = (e, t, o, n, i, r, s) => {
    setupPropertyEditor2_Long(
      this.globals,
      e,
      t,
      o,
      undefined,
      i,
      r,
      s,
      "points"
    );
  };
}
function designer_scaleMode_vbCharacters() {
  this.render = (e, t, o, n, i, r, s) => {
    setupPropertyEditor2_Long(
      this.globals,
      e,
      t,
      o,
      undefined,
      i,
      r,
      s,
      "chars"
    );
  };
}
function designer_scaleMode_vbInches() {
  this.render = (e, t, o, n, i, r, s) => {
    setupPropertyEditor2_Long(
      this.globals,
      e,
      t,
      o,
      undefined,
      i,
      r,
      s,
      "inches"
    );
  };
}
function designer_scaleMode_vbMillimeters() {
  this.render = (e, t, o, n, i, r, s) => {
    setupPropertyEditor2_Long(this.globals, e, t, o, undefined, i, r, s, "mms");
  };
}
function designer_scaleMode_vbCentimeters() {
  this.render = (e, t, o, n, i, r, s) => {
    setupPropertyEditor2_Long(this.globals, e, t, o, undefined, i, r, s, "cms");
  };
}
function designer_scaleMode_vbHimetric() {
  this.render = (e, t, o, n, i, r, s) => {
    setupPropertyEditor2_Long(
      this.globals,
      e,
      t,
      o,
      undefined,
      i,
      r,
      s,
      "himetrics"
    );
  };
}
function designer_AboutBox() {
  this.render = (e, t, o, n) => {
    var i = document.createElement("div");
    i.innerText = "{ AboutBox }";
    i.className = "propertyPage";
    e.appendChild(i);
  };
  this.preRender = (e, t, o) => {
    e.style.cursor = "pointer";
  };
  this.ellipsesClick = (e, t, o) => {
    if (this.globals.outstandingSerializationRequests) {
      msgBox(
        "后端编译器似乎繁忙。  检查IDE窗口背后的对话框是否打开。"
      );
      return;
    }
    t = t.substr(1, t.length - 2);
    changeSelectedControlsProperty(this.globals, "_openAboutBox", t);
  };
}
function addPropertySheetEntryInner(
  globals,
  group,
  propertyEditorType,
  customPropertyRenderer,
  propertyNameDiv,
  propertyValueDiv,
  propertyValue,
  propertyValueDescriptor,
  propertyValueRGB,
  propertyScaleFactor,
  propertyScaleOffset
) {
  if (propertyValueDescriptor) {
    propertyValueDiv.title = propertyValueDescriptor;
    propertyNameDiv.title += "\n" + propertyValueDescriptor;
  }
  if (propertyNameDiv.titleOrig === "FontName") {
    customPropertyRenderer = "designer_FontList";
  }
  if (propertyEditorType === "ExceptionOccurred") {
    customPropertyRenderer = undefined;
  }
  var done = false;
  if (customPropertyRenderer !== undefined) {
    var renderer;
    try {
      renderer = eval("new " + customPropertyRenderer);
      renderer.globals = globals;
      if (renderer.preRender) {
        renderer.preRender(
          propertyValueDiv,
          propertyNameDiv.titleOrig,
          propertyValue,
          propertyValueRGB
        );
      }
      if (renderer.render) {
        renderer.render(
          propertyValueDiv,
          propertyNameDiv.titleOrig,
          propertyValue,
          propertyValueRGB,
          propertyNameDiv,
          propertyScaleFactor,
          propertyScaleOffset
        );
        done = true;
      }
      if (renderer.otherDoubleClick) {
        propertyNameDiv.ondblclick = () => {
          renderer.otherDoubleClick();
        };
      }
    } catch {}
  }
  if (done) {
  } else if (propertyEditorType !== undefined) {
    if (propertyEditorType === null) {
      setupPropertyEditor2_Unsupported(
        globals,
        propertyValueDiv,
        propertyNameDiv.titleOrig,
        propertyValue,
        propertyEditorType,
        propertyNameDiv
      );
    } else if (propertyEditorType.toString()[0] == "|") {
      var enumValues = propertyEditorType.substring(1).split("|");
      setupPropertyEditor2_Enumeration(
        globals,
        propertyValueDiv,
        propertyNameDiv.titleOrig,
        propertyValue,
        enumValues,
        propertyNameDiv
      );
    } else if (propertyEditorType.toString()[0] == "^") {
      var enumValues = propertyEditorType.substring(1).split("|");
      enumValues = enumValues.reverse();
      setupPropertyEditor2_Enumeration(
        globals,
        propertyValueDiv,
        propertyNameDiv.titleOrig,
        propertyValue,
        enumValues,
        propertyNameDiv,
        true
      );
    } else if (propertyEditorType === "ExceptionOccurred") {
      setupPropertyEditor2_Exception(
        globals,
        propertyValueDiv,
        propertyNameDiv.titleOrig,
        propertyValue,
        propertyEditorType,
        propertyNameDiv
      );
    } else if (
      propertyEditorType < globals.setupPropertyEditorFunctions2.length
    ) {
      globals.setupPropertyEditorFunctions2[propertyEditorType](
        globals,
        propertyValueDiv,
        propertyNameDiv.titleOrig,
        propertyValue,
        propertyEditorType,
        propertyNameDiv
      );
    } else {
      setupPropertyEditor2_Unsupported(
        globals,
        propertyValueDiv,
        propertyNameDiv.titleOrig,
        propertyValue,
        propertyEditorType,
        propertyNameDiv
      );
    }
  } else {
    if (propertyValue !== null) propertyValueDiv.innerHTML = propertyValue;
  }
  group.appendChild(propertyNameDiv);
  group.appendChild(propertyValueDiv);
  if (propertyValueDescriptor) {
    if (globals.focusedPropertyName === propertyNameDiv.titleOrig) {
      globals.proprtiesBoxFooter.innerText = propertyValueDescriptor;
      if (globals.proprtiesBoxFooter.innerHTML)
        globals.proprtiesBoxFooter.innerHTML =
          globals.infoIcon + globals.proprtiesBoxFooter.innerHTML;
    }
  }
}
function copyTo(e, t, o) {
  var n = t.split(".", 1)[0];
  var i = t.substring(n.length + 1);
  var r = getControlByName(e, n);
  changeProperty(e, r, i, o);
  var s = i == "Left" || i == "Top";
  var a = i == "Width" || i == "Height";
  if (!s || r.properties.Dock === e.tbDockNone) {
    syncDesignerControlToProperties(e, r);
    if (i === "Dock" || (a && r.properties.Dock !== e.tbDockNone)) {
      doAnchoringAdjustments(e, r.parentElement, true);
    }
  }
  undoPoint(e);
  getImageFromServer(e, r);
}
function getMatchingPropertyTypesSubMenu(e, t, o, n, i, r, s, a, l, d) {
  for (const g in i) {
    var c = i[g];
    if (g.substring(0, 17) === "__defaultElement_") {
      if (l) {
        if (JSON.stringify(l) === JSON.stringify(c)) {
          let i = g.substring(17);
          let r = o + "." + i;
          if (r === t) {
          } else {
            n.push({
              name: r,
              onclick: () => {
                copyTo(e, r, d);
              },
            });
          }
        }
      }
    } else if (Array.isArray(c)) {
      var u = i["__defaultElement_" + g];
      var p = false;
      if (s && isObject(u) && u._clsid === s) {
        p = true;
      }
      var f = 0;
      while (f < c.length) {
        let i = c[f];
        let u = o + "." + g + "(" + f + ")";
        if (p) {
          if (u === t) {
          } else if (a === undefined || a === propertyName) {
            n.push({
              name: u,
              onclick: () => {
                copyTo(e, u, d);
              },
            });
          }
        }
        getMatchingPropertyTypesSubMenu(e, t, u, n, i, r, s, a, l, d);
        f++;
      }
    } else if (isObject(c)) {
      getMatchingPropertyTypesSubMenu(e, t, o + "." + g, n, c, r, s, a, l, d);
    } else if (l) {
    } else if (g.substring(0, 9) === "__editor_") {
      if (r === undefined || c === r) {
        let i = g.substring(9);
        let r = o + "." + i;
        if (r === t) {
        } else if (a === undefined || a === i) {
          n.push({
            name: r,
            onclick: () => {
              copyTo(e, r, d);
            },
          });
        }
      }
    }
  }
}
function addPropertySheetEntry(
  globals,
  groupPrefix,
  group,
  propertyName,
  propertyEditorType,
  arrayDefaultElement,
  customPropertyRenderer,
  propertyValue,
  propertyValueDescriptor,
  level,
  propertyValueRGB,
  propertyUnimplemented,
  propertyScaleFactor,
  propertyScaleOffset
) {
  let propertyNameDiv = document.createElement("div");
  propertyNameDiv.className = "propertyName";
  propertyNameDiv.titleOrig =
    (groupPrefix === undefined ? "" : groupPrefix + ".") + propertyName;
  propertyNameDiv.title = propertyNameDiv.titleOrig;
  let propertyValueDiv = document.createElement("div");
  propertyValueDiv.className = "propertyValue";
  if (propertyUnimplemented) {
    propertyNameDiv.classList.add("propertyNameUnimplemented");
    propertyValueDiv.classList.add("propertyValueUnimplemented");
  }
  propertyValueDiv.onmousedown = (e) => {
    if (e.button == 2) {
      propertyValueDiv.classList.add("focusedPropertSheetElement");
      cancelContextMenu(globals, e);
      var t = propertyEditorType;
      var o = isObject(propertyValue) ? propertyValue._clsid : undefined;
      var n = undefined;
      var i = undefined;
      var r = "{" + propertyEditorType + "}";
      if (Number.isInteger(propertyEditorType)) {
        r = propertyValue;
        n = propertyName;
      } else if (Array.isArray(propertyEditorType)) {
        r = "{array}";
        t = undefined;
        i = arrayDefaultElement;
      } else if (propertyEditorType.toString().substring(0, 1) == "|") {
        r = propertyValue;
      }
      globals.vscode.postMessage({
        type: "getClipboardData",
        args: ["text/tbProperty"],
      });
      globals.gotClipboardDataFunction = (s) => {
        var a;
        try {
          a = JSON.parse(s);
        } catch (e) {}
        let l = r;
        var d = [
          {
            name: "复制",
            onclick: (e) => {
              globals.rootElement.oncopy = (e) => {
                globals.rootElement.oncopy = (e) => {
                  document_oncopy(globals, e);
                };
                globals.vscode.postMessage({
                  type: "clipboardCopy",
                  args: [JSON.stringify(propertyValue, null, "\t")],
                });
                if (e) e.preventDefault();
              };
              globals.vscode.postMessage({ type: "copy" });
            },
          },
          {
            name: "粘贴",
            onclick: (e) => {
              changeSelectedControlsProperty(
                globals,
                propertyNameDiv.titleOrig,
                a
              );
            },
          },
          {
            name: "Copy " + (r ? r.toString() : "{unknown}") + " To ▶",
            onreveal: (e) => {
              var r = [];
              globals.allControls.forEach((e) => {
                if (e.properties) {
                  getMatchingPropertyTypesSubMenu(
                    globals,
                    propertyNameDiv.titleOrig,
                    e.properties.Name,
                    r,
                    e.properties,
                    t,
                    o,
                    n,
                    i,
                    l
                  );
                }
              });
              if (r.length == 0) {
                r.push({ name: "{ no matches }", onclick: () => {} });
              }
              showDesignerContextMenu(
                globals,
                globals.contextMenu2,
                e,
                r,
                () => {
                  propertyValueDiv.classList.remove(
                    "focusedPropertSheetElement"
                  );
                }
              );
            },
          },
        ];
        if (customPropertyRenderer == "designer_SpectrumWindows") {
          d.push({
            name: "SYSTEM COLORS ▶",
            onreveal: (e) => {
              var t = [];
              t.push(
                {
                  name: "vbScrollBars",
                  onclick: (e) => {
                    changeSelectedControlsProperty(
                      globals,
                      propertyNameDiv.titleOrig,
                      -2147483648
                    );
                    globals.rootElement.onclick(selectEvent);
                  },
                },
                {
                  name: "vbDesktop",
                  onclick: (e) => {
                    changeSelectedControlsProperty(
                      globals,
                      propertyNameDiv.titleOrig,
                      -2147483647
                    );
                  },
                },
                {
                  name: "vbActiveTitleBar",
                  onclick: (e) => {
                    changeSelectedControlsProperty(
                      globals,
                      propertyNameDiv.titleOrig,
                      -2147483646
                    );
                  },
                },
                {
                  name: "vbInactiveTitleBar",
                  onclick: (e) => {
                    changeSelectedControlsProperty(
                      globals,
                      propertyNameDiv.titleOrig,
                      -2147483645
                    );
                  },
                },
                {
                  name: "vbMenuBar",
                  onclick: (e) => {
                    changeSelectedControlsProperty(
                      globals,
                      propertyNameDiv.titleOrig,
                      -2147483644
                    );
                  },
                },
                {
                  name: "vbWindowBackground",
                  onclick: (e) => {
                    changeSelectedControlsProperty(
                      globals,
                      propertyNameDiv.titleOrig,
                      -2147483643
                    );
                  },
                },
                {
                  name: "vbWindowFrame",
                  onclick: (e) => {
                    changeSelectedControlsProperty(
                      globals,
                      propertyNameDiv.titleOrig,
                      -2147483642
                    );
                  },
                },
                {
                  name: "vbMenuText",
                  onclick: (e) => {
                    changeSelectedControlsProperty(
                      globals,
                      propertyNameDiv.titleOrig,
                      -2147483641
                    );
                  },
                },
                {
                  name: "vbWindowText",
                  onclick: (e) => {
                    changeSelectedControlsProperty(
                      globals,
                      propertyNameDiv.titleOrig,
                      -2147483640
                    );
                  },
                },
                {
                  name: "vbActiveTitleBarText",
                  onclick: (e) => {
                    changeSelectedControlsProperty(
                      globals,
                      propertyNameDiv.titleOrig,
                      -2147483639
                    );
                  },
                },
                {
                  name: "vbActiveBorder",
                  onclick: (e) => {
                    changeSelectedControlsProperty(
                      globals,
                      propertyNameDiv.titleOrig,
                      -2147483638
                    );
                  },
                },
                {
                  name: "vbInactiveBorder",
                  onclick: (e) => {
                    changeSelectedControlsProperty(
                      globals,
                      propertyNameDiv.titleOrig,
                      -2147483637
                    );
                  },
                },
                {
                  name: "vbApplicationWorkspace",
                  onclick: (e) => {
                    changeSelectedControlsProperty(
                      globals,
                      propertyNameDiv.titleOrig,
                      -2147483636
                    );
                  },
                },
                {
                  name: "vbHighlight",
                  onclick: (e) => {
                    changeSelectedControlsProperty(
                      globals,
                      propertyNameDiv.titleOrig,
                      -2147483635
                    );
                  },
                },
                {
                  name: "vbHighlightText",
                  onclick: (e) => {
                    changeSelectedControlsProperty(
                      globals,
                      propertyNameDiv.titleOrig,
                      -2147483634
                    );
                  },
                },
                {
                  name: "vbButtonFace",
                  onclick: (e) => {
                    changeSelectedControlsProperty(
                      globals,
                      propertyNameDiv.titleOrig,
                      -2147483633
                    );
                  },
                },
                {
                  name: "vbButtonShadow",
                  onclick: (e) => {
                    changeSelectedControlsProperty(
                      globals,
                      propertyNameDiv.titleOrig,
                      -2147483632
                    );
                  },
                },
                {
                  name: "vbGrayText",
                  onclick: (e) => {
                    changeSelectedControlsProperty(
                      globals,
                      propertyNameDiv.titleOrig,
                      -2147483631
                    );
                  },
                },
                {
                  name: "vbButtonText",
                  onclick: (e) => {
                    changeSelectedControlsProperty(
                      globals,
                      propertyNameDiv.titleOrig,
                      -2147483630
                    );
                  },
                },
                {
                  name: "vbInactiveTitleBarText",
                  onclick: (e) => {
                    changeSelectedControlsProperty(
                      globals,
                      propertyNameDiv.titleOrig,
                      -2147483629
                    );
                  },
                },
                {
                  name: "vb3DHighlight",
                  onclick: (e) => {
                    changeSelectedControlsProperty(
                      globals,
                      propertyNameDiv.titleOrig,
                      -2147483628
                    );
                  },
                },
                {
                  name: "vb3DDKShadow",
                  onclick: (e) => {
                    changeSelectedControlsProperty(
                      globals,
                      propertyNameDiv.titleOrig,
                      -2147483627
                    );
                  },
                },
                {
                  name: "vb3DLight",
                  onclick: (e) => {
                    changeSelectedControlsProperty(
                      globals,
                      propertyNameDiv.titleOrig,
                      -2147483626
                    );
                  },
                },
                {
                  name: "vbInfoText",
                  onclick: (e) => {
                    changeSelectedControlsProperty(
                      globals,
                      propertyNameDiv.titleOrig,
                      -2147483625
                    );
                  },
                },
                {
                  name: "vbInfoBackground",
                  onclick: (e) => {
                    changeSelectedControlsProperty(
                      globals,
                      propertyNameDiv.titleOrig,
                      -2147483624
                    );
                  },
                },
                {
                  name: "vbHotTrackText",
                  onclick: (e) => {
                    changeSelectedControlsProperty(
                      globals,
                      propertyNameDiv.titleOrig,
                      -2147483622
                    );
                  },
                },
                {
                  name: "vbActiveTitleBarGradient",
                  onclick: (e) => {
                    changeSelectedControlsProperty(
                      globals,
                      propertyNameDiv.titleOrig,
                      -2147483621
                    );
                  },
                },
                {
                  name: "vbInactiveTitleBarGradient",
                  onclick: (e) => {
                    changeSelectedControlsProperty(
                      globals,
                      propertyNameDiv.titleOrig,
                      -2147483620
                    );
                  },
                },
                {
                  name: "vbMenuHighlight",
                  onclick: (e) => {
                    changeSelectedControlsProperty(
                      globals,
                      propertyNameDiv.titleOrig,
                      -2147483619
                    );
                  },
                },
                {
                  name: "vbMenuBarFlat",
                  onclick: (e) => {
                    changeSelectedControlsProperty(
                      globals,
                      propertyNameDiv.titleOrig,
                      -2147483618
                    );
                  },
                }
              );
              showDesignerContextMenu(
                globals,
                globals.contextMenu2,
                e,
                t,
                () => {
                  propertyValueDiv.classList.remove(
                    "focusedPropertSheetElement"
                  );
                  globals.contextMenu.style.visibility = "hidden";
                }
              );
            },
          });
        }
        var c = true;
        if (isObject(propertyValue)) {
          if (!a || !isObject(a) || a._clsid !== propertyValue._clsid) {
            c = false;
          }
        } else {
          if (isObject(a)) {
            c = false;
          } else {
            if (Array.isArray(propertyEditorType)) {
              if (Array.isArray(a)) {
                a.forEach((e) => {
                  if (isObject(arrayDefaultElement)) {
                    if (
                      !e ||
                      !isObject(e) ||
                      e._clsid !== arrayDefaultElement._clsid
                    ) {
                      c = false;
                    }
                  } else {
                    if (Number.isInteger(arrayDefaultElement)) {
                      if (isNaN(parseFloat(e))) {
                        c = false;
                      }
                    }
                  }
                });
              } else {
                c = false;
              }
            } else if (propertyEditorType == 8) {
            } else {
              if (isNaN(parseFloat(a))) {
                c = false;
              }
            }
          }
        }
        d[1].isHidden = !c;
        showDesignerContextMenu(globals, globals.contextMenu, e, d, () => {
          propertyValueDiv.classList.remove("focusedPropertSheetElement");
        });
      };
    }
  };
  if (level) {
    propertyNameDiv.style =
      "width: calc(((100% + " +
      24 * level +
      "px) / 2) - " +
      24 * level +
      "px);";
    propertyValueDiv.style =
      "width: calc(((100% + " + 24 * level + "px) / 2));";
  }
  if (
    customPropertyRenderer ||
    (!isObject(propertyValue) && !Array.isArray(propertyValue))
  ) {
    propertyNameDiv.innerHTML = propertyName;
    addPropertySheetEntryInner(
      globals,
      group,
      propertyEditorType,
      customPropertyRenderer,
      propertyNameDiv,
      propertyValueDiv,
      propertyValue,
      propertyValueDescriptor,
      propertyValueRGB,
      propertyScaleFactor,
      propertyScaleOffset
    );
    if (propertyNameDiv.titleOrig === globals.focusNextRun) {
      try {
        propertyValueDiv.childNodes[0].focus();
      } catch (e) {}
      globals.focusNextRun = undefined;
    }
  } else {
    if (propertyEditorType === undefined) propertyEditorType = "...";
    let e = document.createElement("div");
    e.className = "propertyGroupOuter";
    let t = document.createElement("div");
    t.className = "propertyGroup";
    let o = document.createElement("div");
    o.innerHTML = "&#9654;";
    if (globals.CachedIsExpanded[propertyNameDiv.titleOrig] === true) {
      t.style.display = "block";
      o.className = "treeNodeExpanded";
    } else {
      t.style.display = "none";
      o.className = "treeNodeCollapsed";
    }
    propertyNameDiv.appendChild(o);
    let n = () => {
      propertyOnLostFocus(globals);
      if (propertyValueDescriptor) {
        globals.proprtiesBoxFooter.innerText = propertyValueDescriptor;
        if (globals.proprtiesBoxFooter.innerHTML)
          globals.proprtiesBoxFooter.innerHTML =
            globals.infoIcon + globals.proprtiesBoxFooter.innerHTML;
      } else {
        globals.proprtiesBoxFooter.innerText = "";
      }
      if (o.className === "treeNodeCollapsed") {
        t.style.display = "block";
        o.className = "treeNodeExpanded";
        globals.CachedIsExpanded[propertyNameDiv.titleOrig] = true;
      } else {
        t.style.display = "none";
        o.className = "treeNodeCollapsed";
        globals.CachedIsExpanded[propertyNameDiv.titleOrig] = false;
      }
    };
    var nodeNamePart = document.createElement("div");
    nodeNamePart.innerHTML = " " + propertyName;
    nodeNamePart.className = "treeNodeName";
    propertyNameDiv.appendChild(nodeNamePart);
    propertyValueDiv.innerHTML =
      "<span class='treeObject'> ... { " +
      (Array.isArray(propertyValue) ? "array" : propertyEditorType) +
      " }</span>";
    propertyValueDiv.style.cursor = "pointer";
    propertyNameDiv.style.cursor = "pointer";
    propertyValueDiv.onclick = n;
    propertyNameDiv.onclick = n;
    group.appendChild(propertyNameDiv);
    group.appendChild(propertyValueDiv);
    e.appendChild(t);
    group.appendChild(e);
    if (Array.isArray(propertyValue)) {
      let e = 0;
      propertyValue.forEach((o) => {
        let n = e;
        let i = addPropertySheetEntry(
          globals,
          groupPrefix,
          t,
          propertyName + "(" + n + ")",
          propertyEditorType[e],
          customPropertyRenderer,
          undefined,
          o,
          undefined,
          level + 1
        );
        let r = document.createElement("div");
        r.className = "minusRedIcon";
        r.onclick = (e) => {
          changeSelectedControlsProperty(
            globals,
            propertyNameDiv.titleOrig + "(" + n + ")",
            undefined
          );
          e.stopPropagation();
          return false;
        };
        i.appendChild(r);
        i.draggable = true;
        i.arrayPropertyName = propertyNameDiv.titleOrig;
        i.arrayPropertyIndex = n;
        i.isLastElement = e + 1 == propertyValue.length;
        i.cachedPropertValue = o;
        i.ondragstart = () => {
          globals.dragDropOriginalElement = i;
          i.classList.add("dragStart");
        };
        i.onmousedown = () => {
          i.classList.add("dragStart");
        };
        i.onmouseleave = () => {
          i.classList.remove("dragStart");
        };
        i.onmouseup = () => {
          i.classList.remove("dragStart");
        };
        i.ondrop = (e) => {
          e.preventDefault();
          let t = n;
          if (
            globals.dragDropOriginalElement.arrayPropertyName ===
            i.arrayPropertyName
          ) {
            if (globals.dragDropOriginalElement.arrayPropertyIndex === t) {
              return;
            }
            if (t > globals.dragDropOriginalElement.arrayPropertyIndex) {
              t--;
            }
          }
          changeSelectedControlsProperty(
            globals,
            globals.dragDropOriginalElement.titleOrig,
            undefined
          );
          changeSelectedControlsProperty(
            globals,
            i.arrayPropertyName + "(+" + t + ")",
            globals.dragDropOriginalElement.cachedPropertValue
          );
        };
        i.ondragover = (e) => {
          if (globals.activeDropElement !== undefined) {
            globals.activeDropElement.classList.remove("dropTarget");
          }
          e.preventDefault();
          globals.activeDropElement = i;
          if (
            i.arrayPropertyIndex ===
              globals.dragDropOriginalElement.arrayPropertyIndex ||
            i.arrayPropertyIndex ===
              globals.dragDropOriginalElement.arrayPropertyIndex + 1
          ) {
          } else {
            i.classList.add("dropTarget");
          }
        };
        i.ondragend = (e) => {
          if (globals.activeDropElement !== undefined) {
            globals.activeDropElement.classList.remove("dropTarget");
          }
          globals.activeDropElement = undefined;
          i.classList.remove("dragStart");
        };
        e++;
      });
    } else {
      createPropertySheet(
        globals,
        propertyNameDiv.titleOrig,
        t,
        propertyValue,
        level + 1
      );
    }
    if (arrayDefaultElement !== undefined) {
      var extraEntry = addPropertySheetEntry(
        globals,
        groupPrefix,
        t,
        "",
        0,
        undefined,
        undefined,
        "",
        undefined,
        level + 1
      );
      let e = document.createElement("div");
      e.innerHTML = "+ <span class='addText'>(add)</span>";
      e.className = "treeNodeCollapsed";
      extraEntry.ondragover = (e) => {
        if (globals.activeDropElement !== undefined) {
          globals.activeDropElement.classList.remove("dropTarget");
        }
        e.preventDefault();
        globals.activeDropElement = extraEntry;
        if (globals.dragDropOriginalElement.isLastElement) {
        } else {
          extraEntry.classList.add("dropTarget");
        }
      };
      extraEntry.ondrop = (e) => {
        e.preventDefault();
        changeSelectedControlsProperty(
          globals,
          globals.dragDropOriginalElement.titleOrig,
          undefined
        );
        changeSelectedControlsProperty(
          globals,
          propertyNameDiv.titleOrig + "(+)",
          globals.dragDropOriginalElement.cachedPropertValue
        );
      };
      extraEntry.onmousedown = () => {
        changeSelectedControlsProperty(
          globals,
          propertyNameDiv.titleOrig + "(+)",
          arrayDefaultElement
        );
        var e = Array.isArray(propertyValue) ? propertyValue.length : 0;
        globals.CachedIsExpanded[
          propertyNameDiv.titleOrig + "(" + e + ")"
        ] = true;
        globals.focusNextRun = propertyNameDiv.titleOrig + "(" + e + ")";
      };
      extraEntry.appendChild(e);
    }
  }
  if (customPropertyRenderer !== undefined) {
    var renderer;
    try {
      renderer = eval("new " + customPropertyRenderer);
      renderer.globals = globals;
      if (renderer.ellipsesClick) {
        let e = document.createElement("div");
        e.className = "propertyValueCustomDesignerButton";
        e.innerHTML = "...";
        propertyValueDiv.onclick = () => {
          renderer.ellipsesClick(
            propertyValueDiv,
            propertyNameDiv.titleOrig,
            propertyValue
          );
        };
        propertyValueDiv.appendChild(e);
        propertyNameDiv.ondblclick = () => {
          propertyValueDiv.onclick();
        };
      }
    } catch {}
  }
  if (propertyUnimplemented) {
    propertyNameDiv.innerText = "🛈 " + propertyNameDiv.innerText;
    propertyNameDiv.title =
      "THIS PROPERTY IS NOT YET IMPLEMENTED.  THE VALUE WILL BE IGNORED.";
  }
  return propertyNameDiv;
}
function createPropertySheet(e, t, o, n, i) {
  for (const r in n) {
    if (r.substring(0, 1) !== "_") {
      let s = n["__desc_" + r];
      let a = n["__editor_" + r];
      let l = n["__defaultElement_" + r];
      let d = n["__customDesigner_" + r];
      let c = n["__RGBValue_" + r];
      let u = n[r];
      let p = n["__unimpl_" + r];
      let f = n["__scaleFactor_" + r];
      let g = n["__scaleOffset_" + r];
      let m = false;
      if (a === "IControlArrayCollection") {
        m = true;
      }
      if (r === "Index") {
        if (
          n._clsid === formCLSID_Windows ||
          n._clsid === formCLSID_WindowsUserControl ||
          n._clsid === formCLSID_WindowsPropertyPage
        ) {
          m = true;
        }
      }
      if (!m) addPropertySheetEntry(e, t, o, r, a, l, d, u, s, i, c, p, f, g);
    }
  }
}
function getControlById(e, t) {
  var o = e.allControls.find((e) => e.lastImageRequestId === t);
  if (o === undefined) {
    if (t === e.designer.lastImageRequestId) {
      o = e.designer;
    } else {
      o = null;
    }
  }
  return o;
}
function getControlByName(e, t) {
  var o = t.toLowerCase();
  var n = e.allControls.find((e) => e.properties.Name.toLowerCase() == o);
  if (n === undefined) {
    n = null;
  }
  return n;
}
function getControlArrayMaxIndex(e, t) {
  var o = -1;
  var n = t.toLowerCase();
  e.allControls.forEach((e) => {
    if (e.properties.Name.toLowerCase() == n) {
      if (e.properties.Index > o) {
        o = e.properties.Index;
      }
    }
  });
  return o;
}
function setCustomControlsArray(e, t) {
  e.toolBoxInner.innerHTML = "";
  e.allToolboxItems = [];
  if (t) {
    var o = {};
    t.forEach((e) => {
      if (e.name === "Menu") return;
      e.nameSort = e.name;
      if (e.name === "PictureBox") e.nameSort = "100";
      if (e.name === "Label") e.nameSort = "105";
      if (e.name === "TextBox") e.nameSort = "110";
      if (e.name === "Frame") e.nameSort = "115";
      if (e.name === "CommandButton") e.nameSort = "120";
      if (e.name === "CheckBox") e.nameSort = "130";
      if (e.name === "OptionButton") e.nameSort = "140";
      if (e.name === "ComboBox") e.nameSort = "150";
      if (e.name === "ListBox") e.nameSort = "160";
      if (e.name === "HScrollBar") e.nameSort = "170";
      if (e.name === "VScrollBar") e.nameSort = "180";
      if (e.name === "Timer") e.nameSort = "190";
      if (e.name === "DriveListBox") e.nameSort = "200";
      if (e.name === "DirListBox") e.nameSort = "210";
      if (e.name === "FileListBox") e.nameSort = "220";
      if (e.name === "Shape") e.nameSort = "230";
      if (e.name === "Line") e.nameSort = "240";
      if (e.name === "Image") e.nameSort = "250";
      if (e.name === "Data") e.nameSort = "260";
      if (e.name === "OLE") e.nameSort = "270";
      var t = e.package;
      if (t === "VB" || t === "CustomControlsPackage") {
        t = "工具箱";
      } else {
        t = t;
      }
      if (o[t] === undefined) {
        o[t] = [];
      }
      o[t].push(e);
    });
    Object.keys(o).forEach((e) => {
      let t = o[e];
      t.sort((e, t) => {
        if (e.nameSort < t.nameSort) {
          return -1;
        }
        if (e.nameSort > t.nameSort) {
          return 1;
        }
        return 0;
      });
    });
    if (liveIDEOptions["showToolboxIconsOnly"]) {
      e.toolBoxInner.classList.add("iconsOnly");
    }
    Object.keys(o).forEach((t) => {
      let n = o[t];
      let i = e.toolBoxInner.childNodes
        ? e.toolBoxInner.childNodes[0]
        : undefined;
      let r = t === "工具箱";
      let s = document.createElement("div");
      s.className = "titleBar";
      let a = document.createElement("div");
      a.innerText = t;
      a.className = "selected";
      s.appendChild(a);
      if (r) {
        s.ondblclick = () => {
          if (e.toolBoxInner.classList.contains("iconsOnly")) {
            e.toolBoxInner.classList.remove("iconsOnly");
          } else {
            e.toolBoxInner.classList.add("iconsOnly");
          }
        };
        e.toolBoxInner.insertBefore(s, i);
      } else {
        e.toolBoxInner.appendChild(s);
      }
      let l = document.createElement("div");
      l.className = "toolBoxContent";
      if (r) {
        var d = document.createElement("div");
        d.className = "toolboxItemOuter";
        d.title = "Pointer";
        var c = document.createElement("div");
        c.className = "toolBoxItem";
        if (r)
          c.className = "toolBoxItem toolBoxItemHighContrast toolBoxPointer";
        d.appendChild(c);
        l.appendChild(d);
        var u = document.createElement("div");
        u.className = "toolBoxItemLabel";
        u.innerText = "Pointer";
        d.appendChild(u);
        e.selectedTool = d;
        e.toolBoxPointer = d;
        e.allToolboxItems.push(d);
      }
      if (r) {
        e.toolBoxInner.insertBefore(l, i);
      } else {
        e.toolBoxInner.appendChild(l);
      }
      n.forEach((t) => {
        if (
          t.clsid != formCLSID_Custom &&
          t.clsid != formCLSID_Windows &&
          t.clsid != formCLSID_WindowsUserControl &&
          t.clsid != formCLSID_WindowsPropertyPage
        ) {
          var o = document.createElement("div");
          o.className = "toolboxItemOuter";
          o.title = t.name;
          o.clsid = t.clsid;
          o.controlType = t.name;
          o.controlTypePackage = t.package;
          o.toolInfo = t;
          var n = document.createElement("div");
          n.className = "toolBoxItem";
          if (r) n.className = "toolBoxItem toolBoxItemHighContrast";
          if (t.isActiveXIcon) n.className += " toolBoxActiveXItem";
          n.style.backgroundImage =
            "url('data:image;base64," + t.iconData + "')";
          o.appendChild(n);
          l.appendChild(o);
          var i = document.createElement("div");
          i.className = "toolBoxItemLabel";
          i.innerText = t.name;
          o.appendChild(i);
          e.allToolboxItems.push(o);
        }
      });
    });
    {
      let t = document.createElement("div");
      t.className = "toolBoxContent borderRadius7";
      var n = document.createElement("div");
      n.className = "toolboxItemOuter flexDiv";
      n.title = "Add component...";
      var i = document.createElement("div");
      i.className = "toolBoxItem";
      i.className = "toolBoxItem plusSign";
      n.appendChild(i);
      t.appendChild(n);
      var r = document.createElement("div");
      r.className = "toolBoxItemLabel inlineDiv";
      r.innerText = "更多组件...";
      n.appendChild(r);
      n.onclick = () => {
        var e =
          "组件列表即将来临!\n\n目前，您必须添加普通的COM引用到适当的ActiveX类型库，\n并在窗体设计器中将组件自动添加到这里。";
        var t = createDOMElement(undefined, "div", "simpleMsgBox", e);
        showModalDialog(t, [
          {
            caption: "转到COM引用",
            onclick: () => {
              showReferences();
              hideModalDialog();
            },
          },
          {
            caption: "确定",
            onclick: hideModalDialog,
            isDefaultCancelAction: true,
          },
        ]);
      };
      e.toolBoxInner.appendChild(t);
    }
  }
  e.allToolboxItems.forEach((t) => {
    t.onclick = (o) => {
      e.selectedTool = t;
      if (e.selectedTool === e.toolBoxPointer) {
        e.designer.classList.remove("noControlPointerEventsExceptFrames");
      } else {
        e.designer.classList.add("noControlPointerEventsExceptFrames");
      }
      changeToolboxSelectedItem(e, t);
    };
    t.ondblclick = (t) => {
      unselectAllControls(e);
      e.selectionArea.style.left = (e.designer.properties.Width - 150) / 2;
      e.selectionArea.style.top = (e.designer.properties.Height - 40) / 2;
      if (parseInt(e.selectionArea.style.left) >= 0) {
        e.selectionArea.style.left = e.selectionArea.style.left + "px";
      } else {
        e.selectionArea.style.left = "0px";
      }
      if (parseInt(e.selectionArea.style.top) >= 0) {
        e.selectionArea.style.top = e.selectionArea.style.top + "px";
      } else {
        e.selectionArea.style.top = "0px";
      }
      e.selectionArea.style.width = "150px";
      e.selectionArea.style.height = "40px";
      e.selectionArea.style.visibility = "visible";
      e.rootElement.onmouseup();
    };
  });
}
function refreshAllControlImages(e) {
  e.loadingOverlayInfo.innerHTML +=
    "<br/>&#10004; WebView requesting control bitmaps";
  e.DisableControlsRepaintBoxes = true;
  getImageFromServer(e, e.designer);
  e.allControls.forEach((t) => {
    t.isInitializing = true;
    getImageFromServer(e, t);
  });
  e.DisableControlsRepaintBoxes = false;
}
function flushImageRequestQueue(e) {
  var t = e.queuedImageRequests;
  e.queuedImageRequests = [];
  e.countOfSentServerRequests = 0;
  t.forEach((t) => {
    e.countOfSentServerRequests++;
    e.exampleSocket.send(t);
  });
  if (e.countOfSentServerRequests == 0) {
    e.queuedImageRequests = undefined;
  }
}
function showResyncOverlay(e) {
  e.resyncButton.innerText = "RESYNC";
  e.resyncOverlay.style.visibility = "visible";
  e.resyncButton.onclick = () => {
    e.vscode.postMessage({ type: "ensureImageServerIsReady" });
  };
}
function showLicenceOverlay(e) {
  e.licenceOverlay.style.visibility = "visible";
  e.licenceButton.onclick = () => {
    e.vscode.postMessage({ type: "enterLicenceKey" });
  };
}
function colorToRGBA(e) {
  var t, o;
  t = document.createElement("canvas");
  t.height = 1;
  t.width = 1;
  o = t.getContext("2d");
  o.fillStyle = e;
  o.fillRect(0, 0, 1, 1);
  return o.getImageData(0, 0, 1, 1).data;
}
function byteToHex(e) {
  return ("0" + e.toString(16)).slice(-2);
}
function colorToHex(e) {
  var t, o;
  t = colorToRGBA(e);
  o = [0, 1, 2, 3]
    .map(function (e) {
      return byteToHex(t[e]);
    })
    .join("");
  return "#" + o;
}
function colorToARGBInt(e) {
  var t = colorToRGBA(e);
  return (t[3] << 24) | (t[0] << 16) | (t[1] << 8) | t[2];
}
function colorToABGRInt(e) {
  var t = colorToRGBA(e);
  return (t[3] << 24) | (t[2] << 16) | (t[1] << 8) | t[0];
}
function colorFromARGB(e) {
  var t = (e >> 24) & 255;
  var o = (e >> 16) & 255;
  var n = (e >> 8) & 255;
  var i = e & 255;
  return "rgba(" + o + "," + n + "," + i + "," + t / 255 + ")";
}
function colorFromABGR(e) {
  var t = (e >> 24) & 255;
  var o = (e >> 16) & 255;
  var n = (e >> 8) & 255;
  var i = e & 255;
  return "rgba(" + i + "," + n + "," + o + "," + t / 255 + ")";
}
function CustomDesigner_Grapick_OnClick(e, t, o, n, i) {
  var r = 330;
  o += 20;
  if (t + r > e.rootElement.clientWidth) {
    t = e.rootElement.clientWidth - r;
  }
  var s = 200;
  if (o + s > e.rootElement.clientHeight) {
    o = e.rootElement.clientHeight - s;
  }
  showColorGradientPicker(e, t, o, i, (t) => {
    changeSelectedControlsProperty(e, n, t);
  });
}
function showColorGradientPicker(e, t, o, n, i) {
  const r = new Grapick({
    el: e.gp,
    colorEl: '<input class="colorpicker" type="color"/>',
  });
  r.clear();
  e.gpOuter.style.left = t + "px";
  e.gpOuter.style.top = o + "px";
  e.gpOuter.style.visibility = "visible";
  e.gpOuter.style.display = "block";
  e.gpOK.onclick = () => {
    e.gpOuter.style.visibility = "hidden";
    e.gpOuter.style.display = "none";
    var t = r.getHandlers();
    var o = [];
    t.forEach((e) => {
      var t = {
        _clsid: "{089D4C70-CF05-432E-ADFF-8E72CD22FFA8}",
        PositionPercent: e.position,
        Color: colorToABGRInt(e.color),
      };
      o.push(t);
    });
    i({
      _clsid: "{DE27CE92-3E3D-4738-8688-CFB118F87D88}",
      Values: o,
      Granularity: parseInt(e.gpGranularityValue.value),
    });
  };
  e.gpCancel.onclick = () => {
    e.gpOuter.style.visibility = "hidden";
    e.gpOuter.style.display = "none";
  };
  r.setColorPicker((e) => {
    const t = e.getEl().querySelector(".colorpicker");
    const o = $(t);
    var n = false;
    var i = e.getColor();
    o.spectrum({
      color: i,
      showAlpha: true,
      change(t) {
        n = true;
        e.setColor(t.toRgbString());
      },
      move(t) {
        e.setColor(t.toRgbString(), 0);
      },
      hide(t) {
        if (!n) {
          e.setColor(i);
        }
      },
    });
    return () => {
      o.spectrum("destroy");
    };
  });
  var s = 0;
  while (n.Values[s] !== undefined) {
    var a = n.Values[s];
    r.addHandler(a.PositionPercent, colorFromABGR(a.Color));
    s++;
  }
  e.gpGranularityValue.value = n.Granularity;
}
function dragElement(e, t) {
  var o;
  var n;
  var i = 0,
    r = 0,
    s = 0,
    a = 0;
  if (document.getElementById(t.id + "header")) {
    document.getElementById(t.id + "header").onmousedown = l;
  } else {
    t.onmousedown = l;
  }
  function l(t) {
    o = e.rootElement.onmouseup;
    n = e.rootElement.onmousemove;
    var i = t.target;
    while (i) {
      if (i.classList.contains("gpGnonDraggable")) return;
      i = i.parentElement;
    }
    t = t || window.event;
    t.preventDefault();
    s = t.clientX;
    a = t.clientY;
    e.rootElement.onmouseup = c;
    e.rootElement.onmousemove = d;
  }
  function d(e) {
    e = e || window.event;
    e.preventDefault();
    i = s - e.clientX;
    r = a - e.clientY;
    s = e.clientX;
    a = e.clientY;
    t.style.top = t.offsetTop - r + "px";
    t.style.left = t.offsetLeft - i + "px";
  }
  function c() {
    e.rootElement.onmouseup = o;
    e.rootElement.onmousemove = n;
  }
}
function formDesigner_init(e, t, o, n, i) {
  e.loadingOverlayInfo.innerHTML +=
    "<br/>&#10004; WebView received initialization data";
  e.uniqueId = n;
  e.uniqueFormDesignerId = i;
  if (t !== undefined) {
    if (t.leftSidePanelWidth) {
      e.toolBox.style.width = t.leftSidePanelWidth + "px";
    }
    if (t.rightSidePanelWidth) {
      e.propertiesBox.style.width = t.rightSidePanelWidth + "px";
    }
    if (t.windowsPalette) {
      e.windowsPalette = t.windowsPalette;
    }
  }
  e.initialHTML = e.rootElement.innerHTML;
  e.customControlsArray = o;
  setCustomControlsArray(e, e.customControlsArray);
  initUI(e);
  e.loadingOverlayInfo.innerHTML += "<br/>&#10004; WebView initialization done";
}
function formDesigner_gotClipboardData(e, t) {
  var o = e.gotClipboardDataFunction;
  e.gotClipboardDataFunction = undefined;
  if (o) o(t);
}
function formDesigner_gotPictureBytes(e, t, o) {
  changeSelectedControlsProperty(e, t, o);
}
function formDesigner_imageServerReady(e, t, o) {
  e.attemptCount += 1;
  if (e.attemptCount >= 5) {
    e.loadingOverlayInfo.innerHTML +=
      "<br/>&#215; WebView connection attempt abandoned.  Too many failures.";
    return;
  }
  e.loadingOverlayInfo.innerHTML +=
    "<br/>&#10004; WebView connecting to compiler websocket... (port " +
    t.toString() +
    ")";
  e.licenceOverlay.style.visibility = "hidden";
  e.ImageServerPort = t;
  e.ServerID = o;
  e.exampleSocket = createWebsocketWithFallback(
    "ws://localhost:" + e.ImageServerPort + "/" + e.ServerID
  );
  e.exampleSocket.binaryType = "arraybuffer";
  e.exampleSocket.onopen = () => {
    e.loadingOverlayInfo.innerHTML +=
      "<br/>&#10004; WebView compiler connection established";
    if (!e.gotInitialFormData) {
      e.vscode.postMessage({ type: "serverConnected" });
      flushImageRequestQueue(e);
    } else {
      if (e.rootElement.editorNode.domContainer.classList.contains("hide")) {
        e.AutoResyncWhenNextVisible = true;
      } else {
        refreshAllControlImages(e);
        e.resyncOverlay.style.visibility = "hidden";
      }
    }
  };
  e.exampleSocket.onmessage = (t) => gotServerMessage(e, t);
  e.exampleSocket.onclose = () => {
    e.loadingOverlayInfo.innerHTML +=
      "<br/>&#215; WebView compiler connection CLOSED";
  };
  e.exampleSocket.onerror = () => {
    e.loadingOverlayInfo.innerHTML +=
      "<br/>&#215; WebView compiler connection ERRORED";
  };
}
function formDesigner_formDesignerEventUpdate(e, t, o, n) {
  o.properties.__events = {};
  var i = t.Controls[n];
  if (i !== undefined) {
    for (const e in i) {
      var r = i[e];
      if (r.StartLine !== undefined) {
        o.properties.__events[e] = {
          Uri: t.Uri,
          StartLine: r.StartLine,
          StartCharIndex: r.StartCharIndex,
          EndLine: r.EndLine,
          EndCharIndex: r.EndCharIndex,
          Proc: r.Proc,
          Unimplemented: r.Unimplemented,
        };
      } else {
        o.properties.__events[e] = {
          Uri: t.Uri,
          StartLine: t.InsertLine,
          StartCharIndex: t.InsertCharIndex,
          NewEvent: r.NewEvent,
          Unimplemented: r.Unimplemented,
        };
      }
    }
  }
}
function formDesigner_formDesignerEventsUpdate(e, t) {
  var o;
  if (
    e.designer.properties._clsid === "{33AD5010-6699-11CF-B70C-00AA0060D393}"
  ) {
    o = "UserControl";
  } else {
    o = "Form";
  }
  formDesigner_formDesignerEventUpdate(e, t, e.designer, o);
  e.allControls.forEach((o) => {
    formDesigner_formDesignerEventUpdate(e, t, o, o.properties.Name);
  });
  syncPropertySheet(e);
}
function formDesigner_onDPIChanged(e) {
  showResyncOverlay(e);
}
function formDesigner_revert(e, t) {
  if (!e.gotInitialFormData) {
    e.loadingOverlayInfo.innerHTML +=
      "<br/>&#10004; WebView received form data";
  }
  e.gotInitialFormData = true;
  formDesigner_syncToState(e, t, undefined, false, false);
  if (e.resyncOverlay.style.visibility === "visible") {
    refreshAllControlImages(e);
    e.resyncOverlay.style.visibility = "hidden";
  }
}
function formDesigner_updateControlsList(e, t) {
  e.customControlsArray = t;
  setCustomControlsArray(e, e.customControlsArray);
  if (e.rootElement.editorNode.domContainer.classList.contains("hide")) {
    showResyncOverlay(e);
  }
}
function formDesigner_syncToState(e, t, o, n, i) {
  if (
    t[0]._clsid == formCLSID_Windows ||
    t[0]._clsid == formCLSID_WindowsUserControl ||
    t[0]._clsid == formCLSID_WindowsPropertyPage
  ) {
    e.tbDockNone = "vbDockNone";
    e.tbDockTop = "vbDockTop";
    e.tbDockLeft = "vbDockLeft";
    e.tbDockBottom = "vbDockBottom";
    e.tbDockRight = "vbDockRight";
    e.tbDockFill = "vbDockFill";
    e.WinForms = true;
  } else {
    e.tbDockNone = "tbDockNone";
    e.tbDockTop = "tbDockTop";
    e.tbDockLeft = "tbDockLeft";
    e.tbDockBottom = "tbDockBottom";
    e.tbDockRight = "tbDockRight";
    e.tbDockFill = "tbDockFill";
    e.WinForms = false;
    e.designerMenuBar.style.display = "none";
  }
  if (
    t[0]._clsid === "{33AD5010-6699-11CF-B70C-00AA0060D393}" ||
    t[0]._clsid === "{33AD5018-6699-11CF-B70C-00AA0060D393}"
  ) {
    e.menuBarPreview.classList.add("hide");
  }
  if (t[0]._clsid === "{33AD5018-6699-11CF-B70C-00AA0060D393}") {
    e.designerMenuBar.classList.add("hide");
  }
  e.DisableControlsRepaintBoxes = true;
  e.selectedControls = e.allControls.filter(() => true);
  changedSelectedControls(e);
  e.selectedControls.forEach((e) => {
    e.classList.add("baseControlSelected");
    e.isSelected = true;
  });
  deleteSelectedControls(e);
  var r = t[0].__IDEOptions;
  if (r) {
    e.showGrid = r.showGrid;
    e.alignToGrid = r.alignToGrid;
    e.alignToGridX = parseInt(r.gridWidth);
    e.alignToGridY = parseInt(r.gridHeight);
    e.showOutlines = r.showOutlines;
    e.lockedControls = r.lockedControls;
  }
  if (e.showGrid === undefined) e.showGrid = true;
  if (!e.alignToGrid) e.alignToGrid = false;
  if (!e.alignToGridX) e.alignToGridX = 10;
  if (!e.alignToGridY) e.alignToGridY = 10;
  if (!e.showOutlines) e.showOutlines = false;
  if (e.lockedControls === undefined) e.lockedControls = [];
  if (r) syncIDEOptions(e);
  deserializeForm(e, t);
  deserializeSelection(e, o);
  setUndoRedoButtonsState(e, n, i);
  e.DisableControlsRepaintBoxes = false;
}
function formDesigner_stopIgnoringEscapeKey(e) {
  e.IgnoringEscapeKey = false;
}
var historyPanel;
var editorHistoryLinks = [];
var historyId = 0;
var lastPositions = [];
function validateHistoryFiles() {
  var e = false;
  editorHistoryLinks.forEach((t) => {
    var o = undefined;
    try {
      o = fs.tree.resolvePath("twinbasic:" + t.path);
    } catch (e) {}
    if (!o) {
      historyPanel.tree.rootFolder.removeItem(t.domNode);
      t.domNode.historyNode = undefined;
      t.domNode = undefined;
      t.deleted = true;
      e = true;
    }
  });
  if (e) {
    editorHistoryLinks = editorHistoryLinks.filter(
      (e) => e.deleted === undefined
    );
  }
}
function syncHistoryBookmarks() {
  var e = openEditors.selectedEditorNode.fileNode.getFullPath();
  editorHistoryLinks.forEach((t) => {
    if (t.path === e) {
      t.bookmark = editor.deltaDecorations(
        [],
        [
          {
            range: new monaco.Range(t.lineNumber, 1, t.lineNumber, 1),
            options: { glyphMarginClassName: "" },
          },
        ]
      );
    } else {
      t.bookmark = undefined;
    }
  });
  syncLastPositionsBookmarks();
}
function clearEditorHistoriesWithSamePosition(e, t) {
  editorHistoryLinks.forEach((o) => {
    if (o.path === e) {
      if (o.positionId === t) {
        if (o.bookmark) o.bookmark = editor.deltaDecorations(o.bookmark, []);
        historyPanel.tree.rootFolder.removeItem(o.domNode);
        o.domNode.historyNode = undefined;
        o.domNode = undefined;
        o.deleteMe = true;
      }
    }
  });
  editorHistoryLinks = editorHistoryLinks.filter((e) => !e.deleteMe);
}
function truncateHistoryBeforeAddition() {
  while (editorHistoryLinks.length >= 10) {
    var e = editorHistoryLinks[0];
    if (e.bookmark) {
      e.bookmark = editor.deltaDecorations(e.bookmark, []);
    }
    historyPanel.tree.rootFolder.removeItem(e.domNode);
    e.domNode.historyNode = undefined;
    e.domNode = undefined;
    editorHistoryLinks.splice(0, 1);
  }
}
function syncLastPositionsBookmarks() {
  var e = openEditors.selectedEditorNode.fileNode.getFullPath();
  lastPositions.forEach((t) => {
    if (t.path === e) {
      t.bookmark = editor.deltaDecorations(
        [],
        [
          {
            range: new monaco.Range(t.lineStart, 1, t.lineStart, 1),
            options: { glyphMarginClassName: "" },
          },
        ]
      );
    } else {
      t.bookmark = undefined;
    }
  });
}
function updateLastPosition(e, t) {
  var o =
    lastPositions.length > 0
      ? lastPositions[lastPositions.length - 1]
      : undefined;
  if (o) {
    if (o.path == e) {
      if (t >= o.lineStart && t <= o.lineEnd) {
        return;
      } else if (t == o.lineEnd + 1) {
        o.lineEnd += 1;
        return;
      }
    }
  }
  lastPositions.push({
    path: e,
    lineStart: t,
    lineEnd: t,
    bookmark: editor.deltaDecorations(
      [],
      [
        {
          range: new monaco.Range(t, 1, t, 1),
          options: { glyphMarginClassName: "" },
        },
      ]
    ),
  });
  if (lastPositions.length > 20) {
    o = lastPositions.shift();
    if (o.bookmark) {
      editor.deltaDecorations(o.bookmark, []);
      o.bookmark = undefined;
    }
  }
}
function updateLastPositionBookmarks() {
  lastPositions.forEach((e) => {
    if (e.bookmark) {
      try {
        var t =
          openEditors.selectedEditorNode.monacoModelInstance.getDecorationRange(
            e.bookmark
          ).startLineNumber;
        if (e.lineStart !== t) {
          e.lineStart = t;
        }
      } catch (e) {}
    }
  });
}
function updateHistory(e, t, o) {
  if (o) updateLastPosition(e, o);
  if (!e) return;
  if (!t || t === "") return;
  var n = undefined;
  if (editorHistoryLinks.length > 0) {
    n = editorHistoryLinks.peek();
  }
  if (!n || e !== n.path || t !== n.positionId) {
    clearEditorHistoriesWithSamePosition(e, t);
    truncateHistoryBeforeAddition();
    var i = undefined;
    if (o !== undefined) {
      i = editor.deltaDecorations(
        [],
        [
          {
            range: new monaco.Range(o, 1, o, 1),
            options: { glyphMarginClassName: "" },
          },
        ]
      );
    }
    var r = new Date();
    var s = getShortTime(r);
    var a = historyPanel.tree.rootFolder.addItem(
      "" + historyId++,
      undefined,
      undefined,
      e + " [line: " + o + "]\r\n" + r.toDateString() + " " + r.toTimeString(),
      t,
      undefined,
      s
    );
    a.historyNode = {
      path: e,
      positionId: t,
      bookmark: i,
      lineNumber: o,
      domNode: a,
      shortTime: s,
      time: r,
    };
    editorHistoryLinks.push(a.historyNode);
  } else {
    n.lineNumber = o;
    if (o !== undefined) {
      n.bookmark = editor.deltaDecorations(n.bookmark, [
        {
          range: new monaco.Range(o, 1, o, 1),
          options: { glyphMarginClassName: "" },
        },
      ]);
    }
    var r = new Date();
    n.shortTime = getShortTime(r);
    n.time = r;
    n.domNode.extraInfo = n.shortTime;
    n.domNode.toolTip =
      e + " [line: " + o + "]\r\n" + r.toDateString() + " " + r.toTimeString();
    n.domNode.render();
  }
}
function updateHistoryBookmarks() {
  updateLastPositionBookmarks();
  var e = false;
  editorHistoryLinks.forEach((t) => {
    if (t.bookmark) {
      try {
        var o =
          openEditors.selectedEditorNode.monacoModelInstance.getDecorationRange(
            t.bookmark
          ).startLineNumber;
        if (t.lineNumber !== o) {
          t.lineNumber = o;
          t.domNode.toolTip =
            t.path +
            " [line: " +
            t.lineNumber +
            "]\r\n" +
            t.time.toDateString() +
            " " +
            t.time.toTimeString();
        }
        var n = undefined;
        var i = undefined;
        var r = undefined;
        codeComboSelectors.cachedScopes.forEach((e) => {
          if (o >= e.range.start.line && o <= e.range.end.line) {
            n = e.name;
            e.procedures.forEach((e) => {
              if (o >= e.range.start.line && o <= e.range.end.line) {
                i = e.scopeName;
                if (e.scopeEventName) {
                  r = e.scopeEventName + " [" + e.name + "]";
                } else {
                  r = e.name;
                }
              }
            });
          }
        });
        var s = [];
        if (n) s.push(n);
        if (i) s.push(i);
        if (r) s.push(r.split("[")[0].trim());
        var a = s.join(".");
        if (t.positionId !== a) {
          t.positionId = a;
          t.domNode.displayName = a;
          t.domNode.render();
          e = true;
        }
      } catch (e) {}
    }
  });
  if (e) {
    var t = editorHistoryLinks.length - 1;
    while (t > 0) {
      var o = editorHistoryLinks[t];
      var n = 0;
      while (n < t) {
        var i = editorHistoryLinks[n];
        if (o.positionId === i.positionId) {
          if (i.bookmark) {
            i.bookmark = editor.deltaDecorations(i.bookmark, []);
          }
          historyPanel.tree.rootFolder.removeItem(i.domNode);
          i.domNode.historyNode = undefined;
          i.domNode = undefined;
          editorHistoryLinks.splice(n, 1);
          t--;
        } else {
          n++;
        }
      }
      t--;
    }
  }
}
function unsyncHistoryBookmarks() {
  unsyncLastPositionBookmarks();
  editorHistoryLinks.forEach((e) => {
    e.bookmark = undefined;
  });
}
function unsyncLastPositionBookmarks() {
  lastPositions.forEach((e) => {
    e.bookmark = undefined;
  });
}
function initHistoryPanel() {}
function persistHistoryPanel() {
  var e = [];
  editorHistoryLinks.forEach((t) => {
    var o = {
      path: t.path,
      positionId: t.positionId,
      lineNumber: t.lineNumber,
      shortTime: t.shortTime,
      time: t.time.toISOString(),
    };
    e.push(o);
  });
  return e;
}
function restoreHistoryPanel(e) {
  e.forEach((e) => {
    var t = new Date(e.time);
    var o = historyPanel.tree.rootFolder.addItem(
      "" + historyId++,
      undefined,
      undefined,
      e.path +
        " [line: " +
        e.lineNumber +
        "]\r\n" +
        t.toDateString() +
        " " +
        t.toTimeString(),
      e.positionId,
      undefined,
      e.shortTime
    );
    o.historyNode = {
      path: e.path,
      positionId: e.positionId,
      bookmark: undefined,
      lineNumber: e.lineNumber,
      domNode: o,
      shortTime: e.shortTime,
      time: t,
    };
    editorHistoryLinks.push(o.historyNode);
  });
  validateHistoryFiles();
}
class _historyPanel {
  constructor(e) {
    this.id = 0;
    this.tree = new treeView(
      e,
      "历史",
      "twinbasic-history:",
      false,
      5,
      false
    );
    this.tree.render();
    this.tree.showFolderIcons = false;
    this.tree.autoExpandOnSelect = false;
    this.tree.showTooltips = true;
    this.tree.rootFolder.sort = false;
    this.tree.additionalFolderClassNames = "historyTree";
    this.tree.emptyFolderText = "";
    this.tree.onClickItem = (e, t) => {
      this.onClickItem(e, t);
    };
  }
  onClickItem(e, t) {
    var o = fs.tree.resolvePath("twinbasic:" + t.historyNode.path);
    openEditors.openFile(o, false, false, false, t.historyNode.lineNumber, 1);
  }
}
function createHistoryPanel(e) {
  if (historyPanel) return historyPanel;
  historyPanel = new _historyPanel(e);
}
var RequestDownloadFolderStruture = 0;
var RequestReadFileContent = 1;
var RequestWriteFileContent = 2;
var RequestCreateFileWithContent = 3;
var RequestCreateFolder = 4;
var RequestDelete = 5;
var RequestMoveItem = 6;
var NotificationItemDeleted = 253;
var NotificationFolderCreated = 254;
var NotificationFileCreated = 255;
var fs;
var visualStylesResourceXML = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">\n   <assemblyIdentity\n      type="win32"\n      processorArchitecture="*"\n      name="My_twinBASIC_Application"\n      version="1.0.0.0"\n   />\n   <description>Application description here</description>\n   <dependency>\n      <dependentAssembly>\n         <assemblyIdentity\n            type="win32"\n            processorArchitecture="*"\n            name="Microsoft.Windows.Common-Controls"\n            version="6.0.0.0"\n            publicKeyToken="6595b64144ccf1df"\n            language="*"\n         />\n      </dependentAssembly>\n   </dependency>\n</assembly>`;
var stringTableResource = `[\n    {\n        "id": 101,\n        "name": "MyLocalizedString1",\n        "LCID_0000": "This is my NEUTRAL text for MyLocalizedString1",\n        "LCID_0409": "This is my USA text for MyLocalizedString1",\n        "LCID_0407": "This is my GERMAN text for MyLocalizedString1",\n        "LCID_0809": "This is my UK text for MyLocalizedString1"\n    },\n    {\n        "id": 102,\n        "name": "MyLocalizedString2",\n        "LCID_0000": "This is my NEUTRAL text for MyLocalizedString2",\n        "LCID_0409": "This is my USA text for MyLocalizedString2",\n        "LCID_0407": "This is my GERMAN text for MyLocalizedString2",\n        "LCID_0809": "This is my UK text for MyLocalizedString2"\n    }\n]`;
function createResource(e, t, o) {
  var n =
    fs.tree.rootFolder.entries[Object.keys(fs.tree.rootFolder.entries)[0]];
  var i = n.entries["resources"];
  var r = i.entries[e.toLowerCase()];
  if (!r) {
    var s = n.getFullPath() + "/RESOURCES/" + e;
    fs.createFolder(s, (n, i) => {
      createResourcePart2(e, t, o);
    });
  } else {
    createResourcePart2(e, t, o);
  }
}
function createResourcePart2(e, t, o, n) {
  var i =
    fs.tree.rootFolder.entries[Object.keys(fs.tree.rootFolder.entries)[0]];
  var r = i.entries["resources"];
  var s = r.entries[e.toLowerCase()];
  var a = s.entries[t.toLowerCase()];
  var l = i.getFullPath() + "/RESOURCES/" + e + "/" + t;
  if (a) {
    if (!n) {
      var d = createDOMElement(
        undefined,
        "div",
        "simpleMsgBox",
        "File already exists:\n\n" + l
      );
      showModalDialog(d, [
        {
          caption: "Replace it",
          onclick: () => {
            createResourcePart2(e, t, o, true);
            hideModalDialog();
          },
        },
        {
          caption: "取消",
          onclick: hideModalDialog,
          isDefaultCancelAction: true,
        },
      ]);
      return;
    }
  }
  fs.createFileUTF8(l, o, (e, t) => {
    if (e !== 0) return;
    var o = fs.tree.resolvePath("twinbasic:" + l);
    openEditors.openFile(o, false);
  });
}
function importFileByPath(e) {
  var t = e.split("\\").pop();
  var o = fs.getUICurrentFolder(false);
  var n = o.getFullPath() + "/" + t;
  root.webSocket.request2(RequestImportFile, e, n);
}
async function importFile() {
  var e = await hostAppObject.OpenFiles(
    "Import File(s)...",
    "All Files (*.*)|*.*"
  );
  if (e && e.length > 0) {
    if (e.indexOf("?") == -1) {
      importFileByPath(e);
    } else {
      var t = e.split("?");
      var o = t.shift();
      debugger;
      if (o.slice(-1) !== "\\") o += "\\";
      t.forEach((e) => {
        importFileByPath(o + e);
      });
    }
  }
}
async function IsClipboardValidUris(e) {
  var t = false;
  try {
    var o = await navigator.clipboard.read();
    for (let e = 0; e < o.length; e++) {
      if (!o[e].types.includes("text/html")) {
      } else {
        var n = await o[e].getType("text/html");
        var i = await n.arrayBuffer();
        var r = new TextDecoder().decode(i);
        if (r.indexOf("twinbasic/uris;") === 0) {
          t = true;
        }
      }
    }
  } catch (e) {}
  e(t);
}
function askToEnableWinNativeForms() {
  var e = createDOMElement(
    undefined,
    "div",
    "simpleMsgBoxNoImage",
    "需要的包: Win原生窗体\r\n\r\n您必须首先在此项目中添加“Win原生窗体包”的引用。\r\n\r\n点击`添加Win原生窗体包`后，编译器将会重启，\r\n准备好您添加到此项目中的窗体。"
  );
  showModalDialog(e, [
    {
      caption: "添加Win原生窗体包",
      onclick: () => {
        hideModalDialog();
        addPackageToProject(
          "{F50B82D0-DCAB-43FE-9631-11959D4A4728}",
          "WinNativeForms"
        );
      },
    },
    { caption: "取消", onclick: hideModalDialog },
  ]);
}
function askToCustomControlsForms() {
  var e = createDOMElement(
    undefined,
    "div",
    "simpleMsgBoxNoImage",
    "Package needed: CustomControls\r\n\r\nYou must first add a reference to the CustomControls package in this project.\r\n\r\nAfter clicking `Add CustomControls package`, the compiler will be restarted,\r\nready for you to add forms to this project."
  );
  showModalDialog(e, [
    {
      caption: "Add CustomControls package",
      onclick: () => {
        hideModalDialog();
        addPackageToProject(
          "{697A5CBF-2012-48BD-9D2F-3EA64CDE149A}",
          "CustomControlsPackage"
        );
      },
    },
    { caption: "取消", onclick: hideModalDialog },
  ]);
}
function addPackageToProject(e, t) {
  var o =
    fs.tree.rootFolder.entries[Object.keys(fs.tree.rootFolder.entries)[0]];
  var n = o.entries["settings"];
  fs.readFile(n, (o, i) => {
    var r = new TextDecoder();
    var s = r.decode(i);
    var a = JSON.parse(s);
    a["project.references"].push({
      id: e,
      lcid: 0,
      name: t,
      path32: "",
      path64: "",
      versionMajor: 0,
      versionMinor: 0,
    });
    fs.writeFile(n, JSON.stringify(a, null, "\t"), 0, false, () => {
      if (!projectFilePath) {
        restartCompilerSafely();
      }
    });
  });
}
function syncFileDiagnosticsToEditor(e) {
  if (e.openEditorNode) {
    var t = [];
    if (e.cachedDiagnostics) {
      e.cachedDiagnostics.forEach((e) => {
        t.push({
          severity:
            e.severity == 1
              ? monaco.MarkerSeverity.Error
              : e.severity == 2
              ? monaco.MarkerSeverity.Warning
              : monaco.MarkerSeverity.Info,
          startLineNumber: e.range.start.line + 1,
          startColumn: e.range.start.character + 1,
          endLineNumber: e.range.end.line + 1,
          endColumn: e.range.end.character + 1,
          message: e.message,
        });
      });
    }
    monaco.editor.setModelMarkers(e.openEditorNode.monacoModelInstance, "", t);
  }
}
function syncFileDiagnosticsToExplorer(e) {
  var t;
  if (e.cachedDiagnostics_errorCount) {
    t = "error";
  } else if (e.cachedDiagnostics_warningCount) {
    t = "warning";
  } else {
    t = "";
  }
  doLayoutChanges(() => {
    e.treeItemClass = t;
    e.render(undefined);
    if (e.openEditorNode) {
      e.openEditorNode.treeItemClass = t;
      e.openEditorNode.render(undefined);
      e.openEditorNode.tabElement.classList.remove("error");
      e.openEditorNode.tabElement.classList.remove("warning");
      if (t.length) e.openEditorNode.tabElement.classList.add(t);
    }
  });
}
function showContextMenuAddComponent(e) {
  getProjectSettings((t) => {
    var o = t["project.references"];
    var n = referencesIncludesWindowsForms(o);
    var i = referencesIncludesCustomControlsForms(o);
    showContextMenu(undefined, e.clientX, e.clientY, [
      {
        name: "Add Folder",
        action: () => {
          fs.addItemViaUI("MyFolder", undefined, "folderIcon", addFolder);
        },
        iconClass: "folderIcon",
      },
      {
        name: "Add Form",
        detail: "Windows Form",
        action: () => {
          if (n) {
            fs.addItemViaUI("MyForm", "tbform", "tbIconGreen", addWindowsForm);
          } else {
            askToEnableWinNativeForms();
          }
        },
        isHidden: false,
        iconClass: "tbIconGreen",
      },
      {
        name: "Add Form",
        detail: "Custom Controls",
        action: () => {
          if (i) {
            fs.addItemViaUI(
              "MyForm",
              "tbform",
              "tbIconGreen",
              addCustomControlsForm
            );
          } else {
            askToCustomControlsForms();
          }
        },
        isHidden: false,
        iconClass: "tbIconGreen",
      },
      {
        name: "Add User Control",
        detail: "Windows",
        action: () => {
          if (n) {
            fs.addItemViaUI(
              "MyUserControl",
              "tbcontrol",
              "tbIconGreen",
              addUserControlFormWINDOWS
            );
          } else {
            askToEnableWinNativeForms();
          }
        },
        isHidden: false,
        iconClass: "tbIconGreen",
      },
      {
        name: "Add Property Page",
        detail: "Windows",
        action: () => {
          if (n) {
            fs.addItemViaUI(
              "MyPropertyPage",
              "tbppage",
              "tbIconGreen",
              addPropertyPageFormWINDOWS
            );
          } else {
            askToEnableWinNativeForms();
          }
        },
        isHidden: false,
        iconClass: "tbIconGreen",
      },
      {},
      {
        name: "Add Module",
        detail: ".TWIN supporting Unicode",
        action: () => {
          fs.addItemViaUI("MyModule", "twin", "tbIconRed", addModuleTWIN);
        },
        iconClass: "tbIconRed",
      },
      {
        name: "Add Class",
        detail: ".TWIN supporting Unicode",
        action: () => {
          fs.addItemViaUI("MyClass", "twin", "tbIconRed", addClassTWIN);
        },
        iconClass: "tbIconRed",
      },
      {},
      {
        name: "Add Module",
        detail: ".BAS",
        action: () => {
          fs.addItemViaUI("MyModule", "bas", "tbIconRed", addModuleBAS);
        },
        iconClass: "tbIconBlue",
      },
      {
        name: "Add Class",
        detail: ".CLS",
        action: () => {
          fs.addItemViaUI("MyClass", "cls", "tbIconRed", addClassCLS);
        },
        iconClass: "tbIconOrange",
      },
      {},
      {
        name: "Add Other File",
        detail: "",
        action: () => {
          fs.addItemViaUI("MyFile", "", "", addFileOther);
        },
        iconClass: "tbIconGeneric",
      },
      {
        name: "Import File(s)...",
        detail: "",
        action: () => {
          importFile();
        },
        iconClass: "tbIconGeneric",
      },
      {},
      {
        name: "Add Resource: Visual Styles Manifest",
        detail: "",
        action: () => {
          createResource("MANIFEST", "#1.xml", visualStylesResourceXML);
        },
      },
      {
        name: "Add Resource: String Table",
        detail: "",
        action: () => {
          createResource("STRING", "Strings.json", stringTableResource);
        },
      },
    ]);
  });
}
var template_formCustomControls = `[{"_isNewControl":true,"_clsid":"{18C42F40-B03D-474E-B99E-7853A314E664}","_className":"Form","Name":"$[NAME]$","Width":300,"Height":300,"FormDesignerId":"{$[FORMID]$}"}]`;
var template_formCustomControls_class = `[ Description ("") ]\r\n[ FormDesignerId ("$[FORMID]$") ]\r\n[ PredeclaredId ]\r\nClass $[NAME]$\r\n\r\n\tSub New()\r\n\tEnd Sub\r\n\r\nEnd Class`;
var template_formWINDOWS = `[{"_isNewControl":true,"_clsid":"{33AD4F38-6699-11CF-B70C-00AA0060D393}","_className":"Form","Name":"$[NAME]$","Width":300,"Height":300,"FormDesignerId":"{$[FORMID]$}"}]`;
var template_formWINDOWS_class = `[ Description ("") ]\r\n[ FormDesignerId ("$[FORMID]$") ]\r\n[ PredeclaredId ]\r\nClass $[NAME]$\r\n\r\n\tSub New()\r\n\tEnd Sub\r\n\r\nEnd Class`;
var template_UserControlWINDOWS = `[{"_isNewControl":true,"_clsid":"{33AD5010-6699-11CF-B70C-00AA0060D393}","_className":"UserControl","Name":"$[NAME]$","Width":300,"Height":300,"FormDesignerId":"{$[FORMID]$}"}]`;
var template_UserControlWINDOWS_class = `[ Description ("") ]\r\n[ FormDesignerId ("$[FORMID]$") ]\r\n[ ClassId ("$[CLASSID]$") ]\r\n[ InterfaceId ("$[INTERFACEID]$") ]\r\n[ EventInterfaceId ("$[EVENTINTERFACEID]$") ]\r\n[ COMControl ]\r\nClass $[NAME]$\r\n\r\n\tSub New()\r\n\tEnd Sub\r\n\r\nEnd Class`;
var template_PropertyPageWINDOWS = `[{"_isNewControl":true,"_clsid":"{33AD5018-6699-11CF-B70C-00AA0060D393}","_className":"PropertyPage","Name":"$[NAME]$","Width":300,"Height":300,"FormDesignerId":"{$[FORMID]$}"}]`;
var template_PropertyPageWINDOWS_class = `[ Description ("") ]\r\n[ FormDesignerId ("$[FORMID]$") ]\r\n[ ClassId ("$[CLASSID]$") ]\r\n[ InterfaceId ("$[INTERFACEID]$") ]\r\n[ EventInterfaceId ("$[EVENTINTERFACEID]$") ]\r\n[ COMControl ]\r\nClass $[NAME]$\r\n\r\n\tSub New()\r\n\tEnd Sub\r\n\r\nEnd Class`;
var template_module = `Module $[NAME]$\r\n\r\n\t' add your procedures here\r\n\r\nEnd Module`;
var template_class = `Class $[NAME]$\r\n\r\n\t' add your member fields and procedures here\r\n\r\nEnd Class`;
var template_moduleBAS = `Attribute VB_Name = "$[NAME]$"\r\n\r\n' add your procedures here\r\n`;
var template_classCLS = `VERSION 1.0 CLASS\r\nBEGIN\r\n    MultiUse = -1  'True\r\n    Persistable = 0  'NotPersistable\r\n    DataBindingBehavior = 0  'vbNone\r\n    DataSourceBehavior  = 0  'vbNone\r\n    MTSTransactionMode  = 0\t'NotAnMTSObject\r\nEND\r\nAttribute VB_Name = "$[NAME]$"\r\nAttribute VB_GlobalNameSpace = False\r\nAttribute VB_Creatable = True\r\nAttribute VB_PredeclaredId = False\r\nAttribute VB_Exposed = False\r\n\r\n' add your member fields and procedures here`;
function showRenameDirtyEditorsError(e) {
  var t = createDOMElement(
    undefined,
    "div",
    "simpleMsgBox",
    "Rename/Move failed.  Please close the following editors that are preventing the operation:\n\n" +
      e
  );
  showModalDialog(t, [
    { caption: "确定", onclick: hideModalDialog, isDefaultCancelAction: true },
  ]);
}
function checkForDirtyEditorsAffected(e) {
  var t = [];
  e.forEach((e) => {
    var o = e.getFullPath();
    if (e.isFolder) {
      var n = openEditors.getEditorsAssociatedWithFolder(o, true);
      n.forEach((e) => t.push(e.getFullPath()));
    } else {
      if (e.openEditorNode) {
        if (openEditors.isDirtyEditor(e.openEditorNode)) {
          t.push(o);
        }
      }
    }
  });
  if (t.length > 0) {
    showRenameDirtyEditorsError(t.join("\n"));
    return false;
  }
  return true;
}
function renameItem(e, t) {
  if (!t) return;
  if (e.parentFolder.isRootFolder) {
    var o = false;
    projectTable.forEach((e) => {
      if (e.id == "project.name") {
        if (e.validate(t) !== true) {
          o = true;
        }
      }
    });
    if (o) {
      msgBox("无法重命名项目: 输入的新名称无效。");
      return false;
    }
    var n =
      fs.tree.rootFolder.entries[Object.keys(fs.tree.rootFolder.entries)[0]];
    var i = n.entries["settings"];
    fs.readFile(i, (e, o) => {
      var n = new TextDecoder();
      var r = n.decode(o);
      var s = JSON.parse(r);
      s["project.name"] = t;
      fs.writeFile(i, JSON.stringify(s, null, "\t"), 0, false, () => {
        if (!projectFilePath) {
          restartCompilerSafely();
        }
      });
    });
    return;
  } else if (
    e.parentFolder.parentFolder.isRootFolder &&
    (e.name === "项目设置" ||
      e.name === "Sources" ||
      e.name === "Resources" ||
      e.name === "References" ||
      e.name === "Packages" ||
      e.name === "Miscellaneous" ||
      e.name === "ImportedTypeLibraries")
  ) {
    msgBox("无法重命名: 权限被拒绝。");
    return false;
  }
  if (!renameItemValidate(e, t)) {
    msgBox("无法重命名: 输入的新名称无效。");
    return;
  }
  if (!checkForDirtyEditorsAffected([e])) {
    return;
  }
  var r = e.getFullPath();
  var s = e.parentFolder.getFullPath();
  var a = s + "/" + t;
  if (r === a) {
    return;
  }
  fs.moveItem(r, a, (e, t) => {
    moveBookmarks(r, a);
  });
  var l = findLinkedFile(r);
  if (l) {
    var d = a.split(".");
    d.pop();
    d += "." + l.split(".").pop();
    d = d.split("/").pop();
    msgBox(
      "是否依然重命名 " + l.split("/").pop() + " 为 " + d + " ?",
      ["YES", "NO"],
      (e) => {
        if (e == "YES") {
          var t = fs.tree.resolvePath("twinbasic:" + l);
          renameItem(t, d);
        }
      }
    );
  }
}
function renameItemValidate(e, t) {
  if (!t || t.length === 0) return false;
  var o = t.toLowerCase();
  var n = t.substr(t.length - 1, 1);
  if (e.name.toLowerCase() === o) {
  } else if (n === "." || n === " ") {
    return false;
  } else if (
    t.indexOf("\\") != -1 ||
    t.indexOf("/") != -1 ||
    t.indexOf(":") != -1 ||
    t.indexOf("*") != -1 ||
    t.indexOf("?") != -1 ||
    t.indexOf('"') != -1 ||
    t.indexOf("<") != -1 ||
    t.indexOf(">") != -1 ||
    t.indexOf("|") != -1
  ) {
    return false;
  } else if (e.parentFolder.entries[o] !== undefined) {
    return false;
  }
  return true;
}
function onDragDroppedMoveItems(e, t) {
  if (!checkForDirtyEditorsAffected(e)) {
    return;
  }
  var o = t.getFullPath();
  e.forEach((e) => {
    var t = e.getFullPath();
    fs.moveItem(t, o + "/" + e.name, (e, t) => {});
  });
}
function addFolder(e, t) {
  var o = e + "/" + t;
  fs.createFolder(o, (e, t) => {});
}
function addWindowsForm(e, t) {
  var o = e + "/" + t;
  if (/[ `!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?~]/.test(t)) t = `[${t}]`;
  var n = generateUUID2();
  var i = template_formWINDOWS.replace("$[FORMID]$", n).replace("$[NAME]$", t);
  var r = template_formWINDOWS_class
    .replace("$[FORMID]$", n)
    .replace("$[NAME]$", t);
  root.multiUpdateStart(() => {
    fs.createFileUTF8(o + ".tbform", i, (e, t) => {
      if (e !== 0) {
        root.multiUpdateEnd(() => {});
        return;
      }
      fs.createFileUTF8(o + ".twin", r, (e, t) => {
        if (e !== 0) {
          root.multiUpdateEnd(() => {});
          return;
        }
        root.multiUpdateEnd(() => {
          var e = fs.tree.resolvePath("twinbasic:" + o + ".tbform");
          openEditors.openFile(e, false);
        });
      });
    });
  });
}
function addUserControlFormWINDOWS(e, t) {
  var o = e + "/" + t;
  if (t.indexOf(" ") != -1) t = `[${t}]`;
  var n = generateUUID2();
  var i = generateUUID2();
  var r = generateUUID2();
  var s = generateUUID2();
  var a = template_UserControlWINDOWS
    .replace("$[FORMID]$", n)
    .replace("$[NAME]$", t);
  var l = template_UserControlWINDOWS_class
    .replace("$[FORMID]$", n)
    .replace("$[NAME]$", t)
    .replace("$[CLASSID]$", i)
    .replace("$[INTERFACEID]$", r)
    .replace("$[EVENTINTERFACEID]$", s);
  root.multiUpdateStart(() => {
    fs.createFileUTF8(o + ".tbcontrol", a, (e, t) => {
      if (e !== 0) {
        root.multiUpdateEnd(() => {});
        return;
      }
      fs.createFileUTF8(o + ".twin", l, (e, t) => {
        if (e !== 0) {
          root.multiUpdateEnd(() => {});
          return;
        }
        root.multiUpdateEnd(() => {
          var e = fs.tree.resolvePath("twinbasic:" + o + ".tbcontrol");
          openEditors.openFile(e, false);
        });
      });
    });
  });
}
function addPropertyPageFormWINDOWS(e, t) {
  var o = e + "/" + t;
  if (t.indexOf(" ") != -1) t = `[${t}]`;
  var n = generateUUID2();
  var i = generateUUID2();
  var r = generateUUID2();
  var s = generateUUID2();
  var a = template_PropertyPageWINDOWS
    .replace("$[FORMID]$", n)
    .replace("$[NAME]$", t);
  var l = template_PropertyPageWINDOWS_class
    .replace("$[FORMID]$", n)
    .replace("$[NAME]$", t)
    .replace("$[CLASSID]$", i)
    .replace("$[INTERFACEID]$", r)
    .replace("$[EVENTINTERFACEID]$", s);
  root.multiUpdateStart(() => {
    fs.createFileUTF8(o + ".tbppage", a, (e, t) => {
      if (e !== 0) {
        root.multiUpdateEnd(() => {});
        return;
      }
      fs.createFileUTF8(o + ".twin", l, (e, t) => {
        if (e !== 0) {
          root.multiUpdateEnd(() => {});
          return;
        }
        root.multiUpdateEnd(() => {
          var e = fs.tree.resolvePath("twinbasic:" + o + ".tbppage");
          openEditors.openFile(e, false);
        });
      });
    });
  });
}
function addCustomControlsForm(e, t) {
  var o = e + "/" + t;
  if (t.indexOf(" ") != -1) t = `[${t}]`;
  var n = generateUUID2();
  var i = template_formCustomControls
    .replace("$[FORMID]$", n)
    .replace("$[NAME]$", t);
  var r = template_formCustomControls_class
    .replace("$[FORMID]$", n)
    .replace("$[NAME]$", t);
  root.multiUpdateStart(() => {
    fs.createFileUTF8(o + ".tbform", i, (e, t) => {
      if (e !== 0) {
        root.multiUpdateEnd(() => {});
        return;
      }
      fs.createFileUTF8(o + ".twin", r, (e, t) => {
        if (e !== 0) {
          root.multiUpdateEnd(() => {});
          return;
        }
        root.multiUpdateEnd(() => {
          var e = fs.tree.resolvePath("twinbasic:" + o + ".tbform");
          openEditors.openFile(e, false);
        });
      });
    });
  });
}
function addModuleTWIN(e, t) {
  var o = e + "/" + t;
  if (t.indexOf(" ") != -1) t = `[${t}]`;
  var n = template_module.replace("$[NAME]$", t);
  fs.createFileUTF8(o + ".twin", n, (e, t) => {
    if (e !== 0) return;
    var n = fs.tree.resolvePath("twinbasic:" + o + ".twin");
    openEditors.openFile(n, false);
  });
}
function addClassTWIN(e, t) {
  var o = e + "/" + t;
  if (t.indexOf(" ") != -1) t = `[${t}]`;
  var n = template_class.replace("$[NAME]$", t);
  fs.createFileUTF8(o + ".twin", n, (e, t) => {
    if (e !== 0) return;
    var n = fs.tree.resolvePath("twinbasic:" + o + ".twin");
    openEditors.openFile(n, false);
  });
}
function addModuleBAS(e, t) {
  var o = e + "/" + t;
  var n = template_moduleBAS.replace("$[NAME]$", t);
  fs.createFileANSI(o + ".bas", n, (e, t) => {
    if (e !== 0) return;
    var n = fs.tree.resolvePath("twinbasic:" + o + ".bas");
    openEditors.openFile(n, false);
  });
}
function addClassCLS(e, t) {
  var o = e + "/" + t;
  var n = template_classCLS.replace("$[NAME]$", t);
  fs.createFileANSI(o + ".cls", n, (e, t) => {
    if (e !== 0) return;
    var n = fs.tree.resolvePath("twinbasic:" + o + ".cls");
    openEditors.openFile(n, false);
  });
}
function addFileOther(e, t) {
  var o = e + "/" + t;
  fs.createFileUTF8(o, "", (e, t) => {
    if (e !== 0) return;
    var n = fs.tree.resolvePath("twinbasic:" + o);
    openEditors.openFile(n, false);
  });
}
function getIconClassType(e, t) {
  var o;
  var n = e.split(".").pop().toLowerCase();
  if (n == "twin") {
    o = "tbIconRed";
  } else if (n == "bas") {
    o = "tbIconBlue";
  } else if (n == "cls") {
    o = "tbIconOrange";
  } else if (n == "tbform" || n == "tbcontrol" || n == "tbppage") {
    o = "tbIconGreen";
  } else if (e === "项目设置") {
    o = "tbIconSettings";
  } else if (t.name === "References") {
    o = "tbIconReference";
  } else {
    o = "tbIconGeneric";
  }
  return o;
}
function getProjectSettings(e) {
  var t =
    fs.tree.rootFolder.entries[Object.keys(fs.tree.rootFolder.entries)[0]];
  var o = t.entries["项目设置"];
  fs.readFile(o, (t, o) => {
    var n = new TextDecoder();
    var i = n.decode(o);
    var r = JSON.parse(i);
    e(r);
  });
}
function referencesIncludesGuid(e, t) {
  var o = false;
  e.forEach((e) => {
    if (e.id == t) {
      o = true;
    }
  });
  return o;
}
function referencesIncludesWindowsForms(e) {
  return (
    referencesIncludesGuid(e, "{566498A8-8F6E-4BC7-869E-2A50C8CB460B}") ||
    referencesIncludesGuid(e, "{F50B82D0-DCAB-43FE-9631-11959D4A4728}")
  );
}
function referencesIncludesCustomControlsForms(e) {
  return (
    referencesIncludesGuid(e, "{EA18E2B1-80BA-478D-AC7C-E955E6AA1B05}") ||
    referencesIncludesGuid(e, "{697A5CBF-2012-48BD-9D2F-3EA64CDE149A}")
  );
}
function findLinkedFile(e) {
  var t = e.split(".");
  var o = t.pop();
  var n = undefined;
  if (o === "twin") {
    var i = t.join(".") + ".tbform";
    var r = t.join(".") + ".tbcontrol";
    var s = t.join(".") + ".tbppage";
    if (fs.tree.resolvePath("twinbasic:" + i)) {
      n = i;
    } else if (fs.tree.resolvePath("twinbasic:" + r)) {
      n = r;
    } else if (fs.tree.resolvePath("twinbasic:" + s)) {
      n = s;
    }
  } else if (o === "tbform" || o === "tbcontrol" || o === "tbppage") {
    var a = t.join(".") + ".twin";
    if (fs.tree.resolvePath("twinbasic:" + a)) {
      n = a;
    }
  }
  return n;
}
class RemoteFileSystem {
  constructor(e) {
    this.tree = new treeView(
      e,
      "项目管理器",
      "twinbasic:",
      true,
      5,
      false
    );
    this.tree.rootFolder.cachedDiagnostics_childErrorCount = 0;
    this.tree.rootFolder.cachedDiagnostics_childWarningCount = 0;
    this.tree.render();
    this.tree.onClickItem = (e, t) => {
      this.onClickItem(e, t);
    };
    this.tree.onDblClickItem = (e, t) => {
      this.onDblClickItem(e, t);
    };
    this.tree.onRightClickItem = (e, t) => {
      this.onRightClickItem(e, t);
    };
    this.tree.onRightClickFolder = (e, t) => {
      this.onRightClickItem(e, t);
    };
    this.tree.onDragDropped = onDragDroppedMoveItems;
    this.tree.onRenameItem = renameItem;
    this.tree.onRenameValidate = renameItemValidate;
    this.tree.caseSensitiveEntries = false;
    this.tree.autoHideEntriesBeginningWithDot = true;
    this.OutOfOrderPendingNotifications = [];
    this.pendingFileSystemCallbacks = [];
    this.currentFileSystemStructureVersion = BigInt(-1);
    var t = createDOMElement(
      this.tree.sectionHeader,
      "div",
      "panelHeaderIcon plusIcon"
    );
    t.onclick = (e) => {
      showContextMenuAddComponent(e);
      e.stopPropagation();
      return false;
    };
  }
  getExpandedFolders() {
    var e = [];
    this.tree.rootFolder.enumerateContent(true, (t) => {
      if (t.isFolder && !t.isCollapsed) {
        e.push(t.getFullPath());
      }
      return true;
    });
    return e;
  }
  getUICurrentFolder(e) {
    var t =
      fs.tree.rootFolder.entries[Object.keys(fs.tree.rootFolder.entries)[0]];
    t = t.entries["sources"];
    var o;
    if (fs.tree.selectedItem) {
      if (fs.tree.selectedItem.isFolder) {
        o = fs.tree.selectedItem;
      } else {
        o = fs.tree.selectedItem.parentFolder;
      }
      if (e) {
        if (o.getFullPath().indexOf(t.getFullPath()) != 0) {
          o = t;
        }
      }
    } else {
      o = t;
    }
    return o;
  }
  addItemViaUI(e, t, o, n) {
    var i = e;
    var r = e + (t ? "." + t : "");
    var s = this.getUICurrentFolder(t ? true : false);
    if (s.isCollapsed) s.expand();
    var a = 2;
    while (s.entries[r.toLowerCase()] !== undefined) {
      e = i + a.toString();
      r = e + (t ? "." + t : "");
      a++;
    }
    var l = s.addItem("", o, undefined, undefined, undefined, true);
    l.rename = (e, o) => {
      try {
        s.removeItem(l);
      } catch (e) {}
      if (o && o.length > 0) {
        if (t) {
          var i = o.split(".");
          if (i.length > 1 && i.pop().toLowerCase() === t.toLowerCase()) {
            o = o.substring(0, o.length - (t.length + 1));
          }
        }
        if (!renameItemValidate(e, o + (t ? "." + t : ""))) {
          msgBox("无法创建: 输入的新名称无效。");
          return;
        }
        n(s.getFullPath(), o);
      }
    };
    document.getElementById("renameInput").value = r;
    document.getElementById("renameInput").onclick = (e) => {
      e.stopPropagation();
      return false;
    };
    document.getElementById("renameInput").ondblclick = (e) => {
      e.stopPropagation();
      return false;
    };
    l.domObject.focus();
    setTimeout(() => {
      document.getElementById("renameInput").setSelectionRange(0, e.length);
    }, 0);
    l.domObject.scrollIntoView({ block: "center" });
  }
  connect(e, t) {
    this.webSocket = new webSocket(
      "ws://localhost:" + e + "/" + compilerPassKey + "/fs",
      this
    );
    this.callback = t;
  }
  onConnected() {
    this.webSocket.request0(RequestDownloadFolderStruture, (e, t) => {
      if (e == 0) {
        this.currentFileSystemStructureVersion = new DataView(
          t,
          0,
          8
        ).getBigInt64(0, true);
        var o = new TextDecoder().decode(t.slice(8));
        this.syncToRemoteFileSystemJSON(o);
        this.callback();
      }
    });
  }
  processNotification(e, t, o) {
    this.currentFileSystemStructureVersion = e;
    if (t === NotificationFileCreated) {
      const e = new DataView(o);
      const d = e.getInt32(0, true);
      const c = o.slice(4);
      var n = new TextDecoder();
      var i = n.decode(c);
      var r = i.split("/");
      var s = r.slice(0, -1).join("/");
      var a = r.pop();
      var l = fs.tree.resolvePath("twinbasic:" + s);
      if (!l) alert("文件系统通知错误: " + t);
      let u = l.addItem(a, getIconClassType(a, l));
      u.readOnly = d & 1;
      u.lastSaved_ideVersionId = 0;
      u.ideVersionId = 0;
      u.cachedDiagnostics_errorCount = 0;
      u.cachedDiagnostics_warningCount = 0;
    } else if (t === NotificationFolderCreated) {
      const e = new DataView(o);
      const d = e.getInt32(0, true);
      const c = o.slice(4);
      var n = new TextDecoder();
      var i = n.decode(c);
      var r = i.split("/");
      var s = r.slice(0, -1).join("/");
      var a = r.pop();
      var l = fs.tree.resolvePath("twinbasic:" + s);
      if (!l) alert("文件系统通知错误: " + t);
      let u = l.addFolder(a);
      u.readOnly = d & 1;
      u.cachedDiagnostics_childErrorCount = 0;
      u.cachedDiagnostics_childWarningCount = 0;
    } else if (t === NotificationItemDeleted) {
      var n = new TextDecoder();
      var i = n.decode(o);
      var d = fs.tree.resolvePath("twinbasic:" + i);
      if (!d) alert("文件系统通知错误: " + t);
      doLayoutChanges(() => {
        if (d.isFolder) {
          updateFolderErrorCounts(
            d,
            -d.cachedDiagnostics_childErrorCount,
            -d.cachedDiagnostics_childWarningCount
          );
        } else {
          if (
            d.cachedDiagnostics_errorCount ||
            d.cachedDiagnostics_warningCount
          ) {
            updateFolderErrorCounts(
              d,
              -d.cachedDiagnostics_errorCount,
              -d.cachedDiagnostics_warningCount
            );
          }
          d.cachedDiagnostics_errorCount = 0;
          d.cachedDiagnostics_warningCount = 0;
          problemsPanel.syncFileProblems(d);
        }
        d.parentFolder.removeEntry(d);
        if (d.isFolder) {
          openEditors.closeAllEditorsInFolder(d.getFullPath());
          problemsPanel.removeProblemsWithinFolder(d.getFullPath());
        } else {
          openEditors.closeEditor(d.getFullPath());
        }
      });
      if (this.tree.selectedItem === d) {
        this.tree.selectedItem = undefined;
        d.parentFolder.onClick({
          ctrlKey: false,
          shiftKey: false,
          dontToggle: true,
        });
      }
      validateHistoryFiles();
    } else {
      alert("文件系统通知: " + t);
    }
    while (this.pendingFileSystemCallbacks.length) {
      var c = this.pendingFileSystemCallbacks.findIndex(
        (t) => t.FSVersion <= e
      );
      if (c == -1) break;
      var u = this.pendingFileSystemCallbacks.splice(c, 1);
      try {
        u[0].callback();
      } catch (e) {}
    }
  }
  onNotification(e, t) {
    var o = new DataView(t, 0, 8).getBigInt64(0, true);
    t = t.slice(8);
    if (o != this.currentFileSystemStructureVersion + 1n) {
      this.OutOfOrderPendingNotifications.push({
        FSVersion: o,
        notificationCode: e,
        notificationData: t,
      });
    } else {
      this.processNotification(o, e, t);
      while (this.OutOfOrderPendingNotifications.length) {
        var n = this.OutOfOrderPendingNotifications.findIndex(
          (e) => e.FSVersion == this.currentFileSystemStructureVersion + 1n
        );
        if (n == -1) break;
        var i = this.OutOfOrderPendingNotifications.splice(n, 1);
        this.processNotification(
          i[0].FSVersion,
          i[0].notificationCode,
          i[0].notificationData
        );
      }
    }
  }
  readFile(e, t) {
    this.webSocket.request1(RequestReadFileContent, e.getFullPath(), t);
  }
  writeFile(e, t, o, n, i) {
    this.webSocket.request2a(
      RequestWriteFileContent,
      o,
      n,
      e.getFullPath(),
      t,
      i
    );
  }
  doAfterSync(e, t) {
    if (this.currentFileSystemStructureVersion >= e) {
      t();
    } else {
      this.pendingFileSystemCallbacks.push({ FSVersion: e, callback: t });
    }
  }
  deleteItem(e, t) {
    this.webSocket.request1(RequestDelete, e, (o, n) => {
      deleteBookmarks(e);
      if (t) {
        var i = new DataView(n, 0, 8).getBigInt64(0, true);
        this.doAfterSync(i, () => {
          t(o, n.slice(8));
        });
      }
    });
  }
  createFolder(e, t) {
    this.webSocket.request1(RequestCreateFolder, e, (e, o) => {
      if (t) {
        var n = new DataView(o, 0, 8).getBigInt64(0, true);
        this.doAfterSync(n, () => {
          t(e, o.slice(8));
        });
      }
    });
  }
  moveItem(e, t, o) {
    this.webSocket.request2(RequestMoveItem, e, t, (e, t) => {
      if (o) {
        var n = new DataView(t, 0, 8).getBigInt64(0, true);
        this.doAfterSync(n, () => {
          o(e, t.slice(8));
        });
      }
    });
  }
  createFile(e, t, o, n) {
    this.webSocket.request2a(
      RequestCreateFileWithContent,
      0,
      o,
      e,
      t,
      (e, t) => {
        if (n) {
          var o = new DataView(t, 0, 8).getBigInt64(0, true);
          this.doAfterSync(o, () => {
            n(e, t.slice(8));
          });
        }
      }
    );
  }
  createFileUTF8(e, t, o) {
    var n = new TextEncoder();
    return this.createFile(e, n.encode(t), 0, o);
  }
  createFileANSI(e, t, o) {
    var n = new TextEncoder();
    return this.createFile(e, n.encode(t), 1, o);
  }
  onClickItem(e, t) {
    openEditors.openFile(t, true, e.ctrlKey, e.shiftKey);
  }
  onDblClickItem(e, t) {
    if (t.isFolder) return;
    openEditors.openFile(t, false, e.ctrlKey, e.shiftKey);
  }
  onRightClickItem(e, t) {
    this.tree.changeSelection(t, e.ctrlKey || t.isSelected, e.shiftKey);
    IsClipboardValidUris((o) => {
      var n = false;
      var i = this.tree.getSelectedNonOverlappingNodes();
      i.forEach((e) => {
        if (e.readOnly) n = true;
      });
      showContextMenu(undefined, e.clientX, e.clientY, [
        {
          name: "添加",
          detail: "➤",
          hoverAction: (t) => {
            showContextMenuAddComponent({
              clientX: e.clientX + t.getBoundingClientRect().width,
              clientY: e.clientY,
            });
          },
          unhoverAction: () => {
            SubMenuRelease();
          },
        },
        {},
        {
          name: "剪切",
          action: () => {
            var e = new Blob(
              ["twinbasic/uris;*;" + this.tree.getSelectedItemsIds().join(";")],
              { type: "text/html" }
            );
            navigator.clipboard.write([new ClipboardItem({ "text/html": e })]);
          },
          isHidden: t.isFolder || n ? true : false,
        },
        {
          name: "复制",
          action: () => {
            var e = new Blob(
              ["twinbasic/uris;" + this.tree.getSelectedItemsIds().join(";")],
              { type: "text/html" }
            );
            navigator.clipboard.write([new ClipboardItem({ "text/html": e })]);
          },
          isHidden: t.isFolder ? true : false,
        },
        {
          name: "粘贴",
          action: () => {
            navigator.clipboard.read().then((e) => {
              for (let t = 0; t < e.length; t++) {
                if (!e[t].types.includes("text/html")) {
                  msgBox("无法从剪贴板中读取数据");
                } else {
                  e[t].getType("text/html").then((e) => {
                    e.arrayBuffer().then((e) => {
                      var t = new TextDecoder().decode(e);
                      if (t.indexOf("twinbasic/uris;") === 0) {
                        var o = t.split(";");
                        var n = false;
                        o.forEach((e) => {
                          if (e === "twinbasic/uris") {
                          } else if (e === "*") {
                            n = true;
                          } else {
                            var t = this.tree.resolvePath("twinbasic:" + e);
                            if (t) {
                              var o = this.tree.selectedItem;
                              if (!o.isFolder) o = o.parentFolder;
                              var i = o.getFullPath() + "/" + t.name;
                              if (n && o === t.parentFolder) {
                                return;
                              }
                              var r = i.split(".").pop();
                              var s = i.substring(0, i.length - (r.length + 1));
                              var a = 1;
                              while (1) {
                                var l = this.tree.resolvePath("twinbasic:" + i);
                                if (!l) break;
                                if (a == 1) {
                                  i = s + " copy." + r;
                                } else {
                                  i = s + " copy " + a + "." + r;
                                }
                                a++;
                              }
                              root.multiUpdateStart(() => {
                                this.readFile(t, (e, o) => {
                                  var r = e === 1;
                                  this.createFile(
                                    i,
                                    new Uint8Array(o),
                                    r ? 1 : 0,
                                    (e) => {
                                      if (e === 0) {
                                        if (n) {
                                          this.deleteItem(
                                            t.getFullPath(),
                                            () => {
                                              root.multiUpdateEnd(() => {});
                                            }
                                          );
                                        } else {
                                          root.multiUpdateEnd(() => {});
                                        }
                                      }
                                    }
                                  );
                                });
                              });
                            }
                          }
                        });
                      }
                    });
                  });
                }
              }
            });
          },
          isHidden: o ? false : true,
        },
        {
          name: "复制路径",
          action: () => {
            navigator.clipboard.writeText(
              this.tree.getSelectedItemsIds().join(";")
            );
          },
        },
        {
          name: "以 JSON 格式查看",
          action: () => {
            fs.readFile(this.tree.selectedItem, (e, t) => {
              var o = new TextDecoder();
              var n = o.decode(t);
              displayVirtualFileInMonaco({
                displayName: "JSON: '" + this.tree.selectedItem.name + "':",
                text:
                  "\r\n/*\r\n\tURI: " +
                  this.tree.selectedItem.getFullPath() +
                  "\r\n\tSNAPSHOT: " +
                  new Date().toDateString() +
                  " " +
                  new Date().toTimeString() +
                  "\r\n*/\r\n\r\n" +
                  n,
                lang: "json",
              });
            });
          },
          isHidden:
            !(
              this.tree.selectedItem.parentFolder &&
              this.tree.selectedItem.parentFolder.name === "Packages"
            ) &&
            (["tbform", "tbcontrol", "tbppage"].indexOf(
              this.tree.selectedItem.name.split(".").pop().toLowerCase()
            ) == -1 ||
              this.tree.getSelectedItemsCount() > 1)
              ? true
              : false,
        },
        {
          name: "重命名",
          action: () => {
            this.tree.selectedItem.isRenaming = true;
            this.tree.selectedItem.render();
          },
          isHidden: n,
        },
        {
          name: "导出...",
          action: () => {
            var e = this.tree.getSelectedItemsCount();
            getExportPath((e) => {
              var t = this.tree.getSelectedItemsIds();
              t.forEach((t) => {
                exportFileTo(t, e, true);
              });
            }, "警告: 这将覆盖任何现有文件!\n\nExport " + e + " item" + (e > 1 ? "s" : "") + " to:");
          },
        },
        {
          name: "永久删除",
          action: () => {
            var e = () => {
              i.forEach((e) => {
                fs.deleteItem(e.getFullPath());
              });
            };
            if (liveIDEOptions["askBeforeDeleteFiles"]) {
              if (i.length == 1) {
                var t = i[0].getFullPath();
                var o = t.split("/").pop();
                var n = findLinkedFile(t);
                if (n) {
                  var r = createDOMElement(
                    undefined,
                    "div",
                    "simpleMsgBox",
                    "您确定要删除以下文件吗?\n\n" +
                      t +
                      "\n" +
                      n +
                      "\n\n您将无法撤消此操作."
                  );
                  showModalDialog(r, [
                    {
                      caption: "删除全部",
                      onclick: () => {
                        e();
                        fs.deleteItem(n);
                        hideModalDialog();
                      },
                    },
                    {
                      caption: "删除 " + o,
                      onclick: () => {
                        e();
                        hideModalDialog();
                      },
                    },
                    { caption: "取消", onclick: hideModalDialog },
                  ]);
                } else {
                  var r = createDOMElement(
                    undefined,
                    "div",
                    "simpleMsgBox",
                    "您确定要删除 '" +
                      t +
                      "'?\n\n您将无法撤消此操作."
                  );
                  showModalDialog(r, [
                    {
                      caption: "删除",
                      onclick: () => {
                        e();
                        hideModalDialog();
                      },
                    },
                    { caption: "取消", onclick: hideModalDialog },
                  ]);
                }
              } else {
                var r = createDOMElement(
                  undefined,
                  "div",
                  "simpleMsgBox",
                  "您确定要删除所选项目吗?\n\n您将无法撤消此操作."
                );
                showModalDialog(r, [
                  {
                    caption: "删除",
                    onclick: () => {
                      e();
                      hideModalDialog();
                    },
                  },
                  { caption: "取消", onclick: hideModalDialog },
                ]);
              }
            } else {
              e();
            }
          },
          isHidden: n,
        },
      ]);
    });
    return false;
  }
  syncRemoteFileSystemDescriptor(e, t) {
    if (!t.isRootFolder) t.name = e.name;
    t.muteRendering = true;
    e.entries.forEach((e) => {
      if (e.entries) {
        var o = t.addFolder(e.name);
        o.readOnly = e.readOnly;
        o.cachedDiagnostics_childErrorCount = 0;
        o.cachedDiagnostics_childWarningCount = 0;
        this.syncRemoteFileSystemDescriptor(e, o);
      } else {
        var n = t.addItem(e.name, getIconClassType(e.name, t));
        n.readOnly = e.readOnly;
        if (e.hidden) n.isHidden = true;
        n.lastSaved_ideVersionId = 0;
        n.ideVersionId = 0;
        n.cachedDiagnostics_errorCount = 0;
        n.cachedDiagnostics_warningCount = 0;
      }
    });
    t.muteRendering = false;
    t.renderEntries();
  }
  syncToRemoteFileSystemJSON(e) {
    var t = JSON.parse(e);
    this.syncRemoteFileSystemDescriptor(t, this.tree.rootFolder);
  }
}
function createFileExplorer(e) {
  if (fs) return fs;
  var t = new RemoteFileSystem(e);
  fs = t;
  return t;
}
async function referenceLoadFromFile(e) {
  var t = await hostAppObject.OpenTypeLibrary("ignoreMe");
  if (t && t.length > 0) {
    const o = t.split("\\").slice(-1).pop();
    const n =
      e.Uri.split("/").slice(0, -1).join("/") + "/ImportedTypeLibraries/" + o;
    HostReadFileData(t, (t) => {
      fs.createFile(n, t, 0, (t) => {
        if (t === 0) {
          getAvailableTypeLibrariesData(
            e.domContainerInner.globalVars,
            "/ImportedTypeLibraries/" + o
          );
        }
      });
    });
  }
}
var afterInitConfigCallback = undefined;
function getPackages(e, t) {
  serverHttpsGetUtf8(
    "/twinbasic/packages/query?auth=" + packagePublisherSessionID,
    (t) => {
      if (e) e(JSON.parse(t));
    },
    (e) => {
      if (!t && e == 552) {
        packageManagerPanel.showSignInForm();
      } else if (e !== 0) {
        showModalNotification(
          "Failed to connect to the online package server.  Error code " +
            e +
            ".  Check your internet connection, or try again later."
        );
      } else {
        showModalNotification(
          "Failed to connect to the online package server.  Check your internet connection, or try again later."
        );
      }
    }
  );
}
function downloadPackage(e, t, o, n, i, r) {
  debugOutputLine(
    "[PACKAGES] downloading package '" +
      e +
      "/" +
      t +
      "/" +
      o +
      "/" +
      n +
      "/" +
      i +
      "' from the online database...",
    "debugConsoleCompilerInfoText"
  );
  serverHttpsGetBinary(
    "/twinbasic/packages/download?auth=" +
      packagePublisherSessionID +
      "&id=" +
      e +
      "&versionMajor=" +
      t +
      "&versionMinor=" +
      o +
      "&versionRevision=" +
      n +
      "&versionBuild=" +
      i,
    (s) => {
      debugOutputLine(
        "[PACKAGES] downloading package '" +
          e +
          "/" +
          t +
          "/" +
          o +
          "/" +
          n +
          "/" +
          i +
          "' from the online database... [DONE]",
        "debugConsoleCompilerInfoText"
      );
      if (r) r(s);
    },
    (e) => {
      if (!dontRetry && e == 552) {
        packageManagerPanel.showSignInForm();
      } else if (e !== 0) {
        debugOutputLine(
          "[PACKAGES] failed.  Server returned HTTPS code " + e,
          "debugConsoleCompilerInfoText"
        );
      } else {
        debugOutputLine(
          "[PACKAGES] failed.  HTTPS request to server (www.everythingaccess.com) failed.  Try again later.",
          "debugConsoleCompilerInfoText"
        );
      }
    }
  );
}
function importPackage(e, t, o, n, i, r) {
  downloadPackage(t, o, n, i, r, (t) => {
    bufferToBase64Async(t, (t) => {
      debugSocket.request("importPackage", { data64: t }, (t) => {
        const o = "/Packages/" + t.body.packageSymbol;
        getAvailableTypeLibrariesData(e, o);
      });
    });
  });
}
function getAvailableTypeLibrariesData(e, t) {
  debugSocket.request("getTypeLibrariesInfo", {}, (o) => {
    configEditor_gotAvailableTypeLibrariesData(
      e,
      o.body.typeLibraries,
      t,
      o.body.installedPackages,
      o.body.internalPackages
    );
  });
}
async function packageLoadFromFile(e) {
  var t = await hostAppObject.OpenPackage("ignoreMe");
  if (t && t.length > 0) {
    HostReadFileData(t, (t) => {
      bufferToBase64Async(t, (t) => {
        debugSocket.request("importPackage", { data64: t }, (t) => {
          const o = "/Packages/" + t.packageSymbol;
          getAvailableTypeLibrariesData(e, o);
        });
      });
    });
  }
}
function createConfigEditorGlobals(e, t) {
  e.globalVars = {
    uri: t,
    isDirty: false,
    rootElement: e,
    vscode: {
      postMessage: (t) => {
        if (t.type === "packageLoadFromFile") {
          packageLoadFromFile(e.globalVars);
        } else if (t.type === "onChanged") {
          e.globalVars.configData = t.args[0];
          e.globalVars.isDirty = true;
          openEditors.updateDirtyState(e.editorNode);
        } else if (t.type === "askDeleteImportedPackage") {
          var o = t.args[0];
          var n = createDOMElement(
            undefined,
            "div",
            "simpleMsgBox",
            "Also remove the imported package from the filesystem?\n\nThis will delete the folder " +
              o
          );
          showModalDialog(n, [
            {
              caption: "Remove It",
              onclick: () => {
                debugSocket.request(
                  "deletePackage",
                  { packagePath: o },
                  (t) => {
                    getAvailableTypeLibrariesData(e.globalVars);
                    hideModalDialog();
                  }
                );
              },
            },
            { caption: "Leave It", onclick: hideModalDialog },
          ]);
        } else if (t.type === "getOnlinePackages") {
          getPackages((t) => {
            configEditor_gotOnlinePackages(e.globalVars, t);
          });
        } else if (t.type === "importOnlinePackage") {
          var i = t.args[0];
          var r = t.args[1];
          var s = t.args[2];
          var a = t.args[3];
          var l = t.args[4];
          importPackage(e.globalVars, i, r, s, a, l);
        } else if (t.type === "librarySymbolRequest") {
          var d = t.args[0];
          var c = t.args[1];
          debugSocket.request(
            "getTypeLibraryInfo_SymbolRequest",
            { requestInfo: c },
            (t) => {
              if (t.success) {
                configEditor_librarySymbolResponse(
                  e.globalVars,
                  d,
                  t.body.symbolName
                );
              }
            }
          );
        } else if (t.type === "referenceLoadFromFile") {
          referenceLoadFromFile(e.editorNode);
        } else if (t.type === "getAvailableTypeLibrariesData") {
          getAvailableTypeLibrariesData(e.globalVars);
        } else {
          msgBox("来自 postMessage: " + t.type);
        }
      },
    },
    optionsHeader: undefined,
    optionsContainer: undefined,
    headerContainer: undefined,
    schema: [],
    CurrentFilter: undefined,
    onlinePackages: { public: [], private: [] },
    initialHTML: undefined,
    configData: undefined,
    inheritedConfigData: undefined,
    allConfigs: undefined,
    referencesSelect: undefined,
    referencesAvailable: undefined,
    filter: undefined,
    moveReferenceUp: undefined,
    moveReferenceDown: undefined,
    warningsTable: undefined,
    uniqueSymbolRequestId: 0,
    referencesListMode: 1,
    notLoggedInWarning: undefined,
    symbolRequests: [],
    selectedReferenceInfo: undefined,
    selectedReferenceInfo_NameValue: undefined,
    selectedReferenceInfo_LibrarySymbolValue: undefined,
    selectedReferenceInfo_LibraryValue: undefined,
    selectedReferenceInfo_VersionValue: undefined,
    selectedReferenceInfo_LcidValue: undefined,
    selectedReferenceInfo_Path32Value: undefined,
    selectedReferenceInfo_Path64Value: undefined,
    selectedReferenceInfo_PublishedDate: undefined,
    selectedReferenceInfo_Publisher: undefined,
    selectedReferenceInfo_SymbolRequestId: undefined,
    ENABLEDselectedReferenceInfo: undefined,
    ENABLEDselectedReferenceInfo_NameValue: undefined,
    ENABLEDselectedReferenceInfo_LibrarySymbolValue: undefined,
    ENABLEDselectedReferenceInfo_LibraryValue: undefined,
    ENABLEDselectedReferenceInfo_VersionValue: undefined,
    ENABLEDselectedReferenceInfo_LcidValue: undefined,
    ENABLEDselectedReferenceInfo_Path32Value: undefined,
    ENABLEDselectedReferenceInfo_Path64Value: undefined,
    ENABLEDselectedReferenceInfo_PublishedDate: undefined,
    ENABLEDselectedReferenceInfo_Publisher: undefined,
    ENABLEDselectedReferenceInfo_SymbolRequestId: undefined,
    errorContainer: undefined,
    HighlightAfterToggle: null,
    CountOfSelectedTypeLibraries: undefined,
    typeLibrariesAvailable: [],
    installedPackages: [],
    internalPackages: [],
    cachedSearchBoxValueBefore: "",
    afterInitCallback: afterInitConfigCallback,
    root: document.documentElement,
  };
  afterInitConfigCallback = undefined;
  var o = projectTable.find((e) => e.id == "project.startupObject");
  debugSocket.request("getListOfForms", {}, (t) => {
    t.body.list.unshift("Sub Main");
    t.body.list.unshift("(none)");
    o.values = t.body.list.join(",");
    configEditor_init(
      e.globalVars,
      JSONfn_stringify(projectTable),
      e.editorNode.configData,
      [properties],
      warningsTable
    );
  });
}
const fileHandler_config = {
  activated(e, t, o, n) {
    e.type = "ConfigEditor";
    statusLineCol.classList.add("hide");
    codePanelMainInnerMonacoContainer.classList.add("hide");
    codePanelDropDownContainer.classList.add("hideNotCodeEditor");
    changedSize();
    if (!e.domContainer) {
      this.createConfigEditor(e);
    } else {
      e.domContainer.classList.remove("hide");
    }
    e.fileNode.tree.changeSelection(e.fileNode, o, n);
    outlinePanel.syncSymbols([]);
  },
  resyncToFileSystem(e) {
    var t = e.fileNode.getFullPath();
    var o = fs.tree.resolvePath("twinbasic:" + t);
    if (o) {
      e.fileNode = o;
      o.openEditorNode = e;
    } else {
      const o = JSONstringifyOrdered(
        e.domContainerInner.globalVars.configData,
        "\t"
      );
      fs.createFileUTF8(t, o, () => {
        var o = fs.tree.resolvePath("twinbasic:" + t);
        e.fileNode = o;
        o.openEditorNode = e;
      });
    }
  },
  deactivated(e) {
    if (this.isDirty(e) && !e.isSaving) {
      msgBox("警告: 您没有保存设置文件中的更改!");
    }
    e.domContainer.classList.add("hide");
  },
  isDirty(e) {
    return e.domContainerInner.globalVars.isDirty;
  },
  createConfigEditor(e) {
    e.domContainer = createDOMElement(
      codePanelMainInner,
      "div",
      "configEditorContainer"
    );
    e.domContainerInner = createDOMElement(
      e.domContainer,
      "div",
      "configEditorContainerInner"
    );
    e.domContainerInner.innerHTML = `\n                                            <div class='header'>\n                                            </div>\n                                            <div class='optionsHeader'>\n                                            </div>\n                                            <div class='options'>\n                                            </div>\n                                            `;
    e.domContainerInner.editorNode = e;
    e.Uri = e.fileNode.getFullPath();
    e.domContainer.tabIndex = "0";
    createConfigEditorGlobals(e.domContainerInner, e.Uri);
  },
  save(e, t) {
    const o = JSONstringifyOrdered(
      e.domContainerInner.globalVars.configData,
      "\t"
    );
    const n = new TextEncoder();
    var i = n.encode(o);
    e.isSaving = true;
    e.domObject_CloseButton.className = "progressSpinnerIcon";
    fs.writeFile(e.fileNode, i, 0, 0, (o) => {
      e.domObject_CloseButton.className = "tabItemIconRight";
      if (o !== 0) return;
      e.domContainerInner.globalVars.isDirty = false;
      openEditors.updateDirtyState(e);
      e.isSaving = false;
      if (t) t();
    });
  },
  closing(e, t, o) {
    if (t) {
      this.save(e, o);
    } else {
      if (o) o();
    }
  },
  closed(e) {
    e.domContainer.removeChild(e.domContainerInner);
    codePanelMainInner.removeChild(e.domContainer);
    delete e.domContainerInner.globalVars;
    delete e.domContainer.editorNode;
  },
  onFocus(e) {
    e.domContainer.focus();
  },
  onReveal(e, t, o, n) {},
  gotFileData(e, t) {
    var o = new TextDecoder().decode(t);
    try {
      e.configData = JSON.parse(o);
      var n = e.configData["project.exportPathIsV2"];
      var i = e.configData["project.exportPath"];
      if (!n && i) {
        e.configData["project.exportPath"] = i + "${ProjectName}\\";
      }
      e.configData["project.exportPathIsV2"] = true;
      var r = e.configData["project.comInitialization"];
      if (r === undefined) {
        var s = e.configData["project.comThreadingModal"];
        if (s === "MTA - Multi Threaded Apartment") {
          e.configData["project.comInitialization"] =
            "MTA (CoInitializeEx - Multi Threaded Apartment)";
        }
        delete e.configData["project.comThreadingModal"];
      }
      var a = e.configData["project.appTitle"];
      if (a === undefined) {
        e.configData["project.appTitle"] = e.configData["project.description"];
        if (e.configData["project.appTitle"] === undefined) {
          e.configData["project.appTitle"] = "";
        }
      }
    } catch {
      msgBox("错误: 解析配置数据时遇到错误的JSON");
    }
    openEditors.changeSelectedEditor(
      e,
      e.initialOptions.preview,
      e.initialOptions.ctrlKey,
      e.initialOptions.shiftKey
    );
  },
};
const fileHandler_preview = {
  activated(e, t, o, n) {
    e.type = "Preview";
    statusLineCol.classList.add("hide");
    codePanelMainInnerMonacoContainer.classList.add("hide");
    codePanelDropDownContainer.classList.add("hideNotCodeEditor");
    changedSize();
    if (!e.domContainer) {
      e.domContainer = createDOMElement(
        codePanelMainInner,
        "div",
        "embedPreviewContainer"
      );
    } else {
      e.domContainer.classList.remove("hide");
    }
    e.domContainer.innerHTML = "";
    e.domContainer.appendChild(e.embedDomElement);
    e.fileNode.tree.changeSelection(e.fileNode, o, n);
    outlinePanel.syncSymbols([]);
  },
  deactivated(e) {
    e.domContainer.classList.add("hide");
  },
  isDirty(e) {
    return false;
  },
  save(e, t) {
    if (t) t();
  },
  resyncToFileSystem(e) {
    var t = e.fileNode.getFullPath();
    var o = fs.tree.resolvePath("twinbasic:" + t);
    if (o) {
      e.fileNode = o;
      o.openEditorNode = e;
    } else {
    }
  },
  closing(e, t, o) {
    if (o) o();
  },
  closed(e) {},
  onFocus(e) {},
  onReveal(e, t, o, n) {},
  gotFileData(e, t) {
    debugger;
    var o = "";
    switch (e.fileExtension) {
      case "ico":
        o = "image/x-icon";
        break;
      case "cur":
        o = "image/x-icon";
        break;
      case "png":
        o = "image/png";
        break;
      case "gif":
        o = "image/gif";
        break;
      case "jpg":
        o = "image/jpeg";
        break;
      case "jpeg":
        o = "image/jpeg";
        break;
      case "svg":
        o = "image/svg+xml";
        break;
      case "pdf":
        o = "application/pdf";
        break;
      case "bmp":
        o = "image/bmp";
        break;
    }
    e.embedDomElement = createDOMElement(undefined, "embed", "embeddedPreview");
    bufferToBase64Async(t, (t) => {
      e.embedDomElement.src = "data:" + o + ";base64," + t;
      openEditors.changeSelectedEditor(
        e,
        e.initialOptions.preview,
        e.initialOptions.ctrlKey,
        e.initialOptions.shiftKey
      );
    });
  },
};
const fileHandler_twin = {
  activated(e, t, o, n) {
    e.type = "CodeEditor";
    if (isDebugMode) debugOutputLine("activated: " + e.fileNode.getFullPath());
    clearEditor();
    editor.updateOptions({ glyphMargin: true, readOnly: e.fileNode.readOnly });
    editor.setModel(e.monacoModelInstance);
    lineNum.innerText = 1;
    columnNum.innerText = 1;
    if (e.monacoViewState) {
      editor.restoreViewState(e.monacoViewState);
    }
    statusLineCol.classList.remove("hide");
    codePanelMainInnerMonacoContainer.classList.remove("hide");
    codePanelDropDownContainer.classList.remove("hideNotCodeEditor");
    changedSize();
    if (!t) editor.focus();
    e.fileNode.tree.changeSelection(e.fileNode, o, n);
    getSemanticTokensForCurrentFile();
    syncFileDiagnosticsToEditor(e.fileNode);
    syncHistoryBookmarks();
    try {
      e.monacoModelInstance.updateOptions({
        tabSize: liveIDEOptions["tabSize"],
      });
    } catch (e) {}
  },
  deactivated(e) {
    unsyncHistoryBookmarks();
    e.monacoViewState = editor.saveViewState();
    syncActiveBreakLine(-1);
  },
  undo(e) {
    editor.getModel().undo();
    editor.focus();
  },
  redo(e) {
    editor.getModel().redo();
    editor.focus();
  },
  isDirty(e) {
    if (!e.monacoModelInstance) return false;
    return (
      e.openingAltVersionId !== e.monacoModelInstance.getAlternativeVersionId()
    );
  },
  save(e, t) {
    var o = e.fileNode.openEditorNode.monacoModelInstance.getValue();
    e.fileNode.lastSaved_ideVersionId = e.fileNode.ideVersionId;
    e.domObject_CloseButton.className = "progressSpinnerIcon";
    {
      fs.writeFile(
        e.fileNode,
        o,
        e.fileNode.ideVersionId,
        e.isSystemANSIFile ? 1 : 0,
        (o) => {
          e.domObject_CloseButton.className = "tabItemIconRight";
          if (o !== 0) return;
          e.openingAltVersionId =
            e.monacoModelInstance.getAlternativeVersionId();
          openEditors.updateDirtyState(e);
          if (t) t();
        }
      );
    }
  },
  resyncToFileSystem(e) {
    var t = e.fileNode.getFullPath();
    var o = fs.tree.resolvePath("twinbasic:" + t);
    if (o) {
      e.fileNode = o;
      o.openEditorNode = e;
      e.monacoModelInstance.fileNode = o;
      if (openEditors.isDirtyEditor(e)) {
        var n = { versionId: e.monacoModelInstance.getVersionId() };
        e.monacoModelInstance.ourChangeContentHandler(n, true);
      } else {
        openEditors.syncEditorToFileSystem(o);
      }
      syncFileDiagnosticsToEditor(o);
    } else {
      fs.createFileUTF8(t, "", () => {
        var o = fs.tree.resolvePath("twinbasic:" + t);
        e.fileNode = o;
        o.openEditorNode = e;
        e.monacoModelInstance.fileNode = o;
        var n = { versionId: e.monacoModelInstance.getVersionId() };
        e.monacoModelInstance.ourChangeContentHandler(n, true);
      });
    }
  },
  closing(e, t, o) {
    if (t) {
      this.save(e, o);
    } else {
      var n = "twinbasic:" + e.fileNode.getFullPath();
      e.fileNode.ideVersionId++;
      if (isDebugMode)
        debugOutputLine(
          "editorNode.fileNode.ideVersionId: " +
            e.fileNode.ideVersionId.toString()
        );
      e.fileNode.lastSaved_ideVersionId = e.fileNode.ideVersionId;
      lspSocket.event("textDocument/didClose", {
        textDocument: { uri: n },
        docVersion: e.fileNode.lastSaved_ideVersionId,
      });
      o();
    }
  },
  closed(e) {},
  onFocus(e) {
    editor.focus();
  },
  onReveal(e, t, o, n) {
    revealLineInEditor(t, o, n);
  },
  gotFileData(e, t) {
    var o = new TextDecoder().decode(t);
    if (e.monacoModelInstance) {
      e.dontFireContentChanged = true;
      if (e.monacoModelInstance.getValue() !== o) {
        e.monacoModelInstance.setValue(o);
      }
      e.dontFireContentChanged = false;
      e.openingAltVersionId = e.monacoModelInstance.getAlternativeVersionId();
      openEditors.updateDirtyState(e);
      if (openEditors.selectedEditorNode === e) {
        getSemanticTokensForCurrentFile();
      }
      return;
    }
    e.monacoModelInstance = monaco.editor.createModel("", "twinbasic");
    if (liveIDEOptions["tabSize"])
      e.monacoModelInstance.updateOptions({
        tabSize: liveIDEOptions["tabSize"],
      });
    e.monacoModelInstance.fileNode = e.fileNode;
    e.monacoModelInstance.cachedBreakpointLines = [];
    e.monacoModelInstance.setValue(o);
    e.openingAltVersionId = e.monacoModelInstance.getAlternativeVersionId();
    e.monacoModelInstance.ourChangeContentHandler = (t, o, n) => {
      if (e.dontFireContentChanged) return;
      var i = undefined;
      if (t.changes) {
        t.changes.forEach((e) => {
          if (
            e.rangeLength === 0 &&
            e.text.substring(0, 2) === "\r\n" &&
            e.text.substring(2).replaceAll(" ", "").replaceAll("\t", "")
              .length === 0
          ) {
            i = e.range.startLineNumber;
          }
        });
      }
      e.fileNode.ideVersionId = e.fileNode.lastSaved_ideVersionId + t.versionId;
      if (isDebugMode)
        debugOutputLine(
          "(ourChangeContentHandler) editorNode.fileNode.ideVersionId: " +
            e.fileNode.ideVersionId.toString()
        );
      openEditors.updateDirtyState(e);
      var r = e.fileNode.getFullPath();
      var s = "twinbasic:" + r;
      var a = e.monacoModelInstance.getValue();
      var l = [];
      if (e === openEditors.selectedEditorNode) {
        var d = e.monacoModelInstance.cachedBreakpointLines;
        o = o || currentBreakpointDecorations.length !== d.length;
        var c = 0;
        currentBreakpointDecorations.forEach((t) => {
          try {
            var n = e.monacoModelInstance.getDecorationRange(t).startLineNumber;
            l.push(n);
            if (!o) {
              if (d[c] !== n) {
                o = true;
              }
            }
            c++;
          } catch (e) {
            o = true;
          }
        });
        var u = {};
        currentBookmarkDecorations.forEach((t) => {
          try {
            var o = e.monacoModelInstance.getDecorationRange(t).startLineNumber;
            u[o] = true;
          } catch (e) {}
        });
        allBookmarks[r] = u;
      }
      l.sort((e, t) => e - t);
      setTimeout(() => {
        var t = editor.getPosition();
        lspSocket.request(
          "textDocument/didChangeV2",
          {
            textDocument: { uri: s, version: e.fileNode.ideVersionId },
            contentChanges: n ? null : [{ text: a }],
            simpleBreakpoints: o ? l : undefined,
            enterKeyAtLine: i,
            isActiveEditor: e === openEditors.selectedEditorNode,
            caretColumn: t.column,
            caretLine: t.lineNumber,
          },
          (t) => {
            nextScopeUpdateIsAnEdit = true;
            parseDocumentDecorations(e, t.result, e.fileNode.ideVersionId);
          }
        );
      }, 0);
    };
    e.monacoModelInstance.onDidChangeContent(
      e.monacoModelInstance.ourChangeContentHandler
    );
    openEditors.changeSelectedEditor(
      e,
      e.initialOptions.preview,
      e.initialOptions.ctrlKey,
      e.initialOptions.shiftKey
    );
    if (e.initialOptions.line)
      revealLineInEditor(
        e.initialOptions.line,
        e.initialOptions.column,
        e.initialOptions.viewPortTop
      );
  },
};
const formCLSID_Custom = "{18C42F40-B03D-474E-B99E-7853A314E664}";
const formCLSID_Windows = "{33AD4F38-6699-11CF-B70C-00AA0060D393}";
const formCLSID_WindowsUserControl = "{33AD5010-6699-11CF-B70C-00AA0060D393}";
const formCLSID_WindowsPropertyPage = "{33AD5018-6699-11CF-B70C-00AA0060D393}";
const dragPointWidth2 = 9;
const dragPointHeight2 = 9;
var formDesignerInstanceId = 1;
var currentDPI = window.devicePixelRatio;
function initFormDesigners() {
  setInterval(() => {
    if (currentDPI != window.devicePixelRatio) {
      currentDPI = window.devicePixelRatio;
      openEditors.tree.rootFolder.enumerateContent(false, (e) => {
        if (e.fileHandler === fileHandler_tbform) {
          if (e.domContainer) {
            formDesigner_onDPIChanged(e.domContainer.globalVars);
          }
        }
        return true;
      });
    }
    checkMsgBoxesTimeout();
  }, 5e3);
}
function formDesignerEventsUpdate(e) {
  var t = "{" + e.FormDesignerId + "}";
  openEditors.tree.rootFolder.enumerateContent(false, (o) => {
    if (o.fileHandler === fileHandler_tbform) {
      if (o.domContainer) {
        if (o.domContainer.globalVars.state.item.form[0].FormDesignerId === t) {
          formDesigner_formDesignerEventsUpdate(o.domContainer.globalVars, e);
        }
      }
    }
    return true;
  });
}
function switchToCodePart() {
  var e = openEditors.selectedEditorNode;
  var t = e.fileNode.getFullPath();
  t = t.replace(".tbform", ".twin");
  t = t.replace(".tbcontrol", ".twin");
  t = t.replace(".tbppage", ".twin");
  var o = fs.tree.resolvePath("twinbasic:" + t);
  if (o) {
    openEditors.openFile(o, liveIDEOptions["previewDocs"] ? true : false);
  } else {
    msgBox(
      "无法切换设计模式: 此文档不属于表单"
    );
  }
}
function switchToFormPart() {
  var e = openEditors.selectedEditorNode;
  var t = e.fileNode.getFullPath();
  t = t.replace(".twin", ".tbform");
  var o = fs.tree.resolvePath("twinbasic:" + t);
  if (o) {
    openEditors.openFile(o, liveIDEOptions["previewDocs"] ? true : false);
  } else {
    t = t.replace(".tbform", ".tbcontrol");
    o = fs.tree.resolvePath("twinbasic:" + t);
    if (o) {
      openEditors.openFile(o, liveIDEOptions["previewDocs"] ? true : false);
    } else {
      t = t.replace(".tbcontrol", ".tbppage");
      o = fs.tree.resolvePath("twinbasic:" + t);
      if (o) {
        openEditors.openFile(o, liveIDEOptions["previewDocs"] ? true : false);
      } else {
        msgBox(
          "无法切换设计模式: 此文档不属于表单"
        );
      }
    }
  }
}
function toggleFormDesign() {
  var e = openEditors.selectedEditorNode;
  if (e.fileHandler === fileHandler_twin) {
    switchToFormPart();
  } else if (e.fileHandler === fileHandler_tbform) {
    switchToCodePart();
  } else {
    msgBox(
      "无法切换设计模式: 此文档不属于表单"
    );
  }
}
function readFileToIPictureBytes(e, t, o, n) {
  debugSocket.request("getIPictureBytes", { filePath: o }, (o) => {
    if (o.success) {
      formDesigner_gotPictureBytes(e.domContainer.globalVars, t, o.body.base64);
    } else {
      msgBox("加载图片失败: " + o.message);
    }
  });
}
async function openFilePictureBytes(e, t) {
  var o = await hostAppObject.OpenImage("ignoreMe");
  if (o && o.length > 0) {
    readFileToIPictureBytes(e, t, o);
  }
}
async function openFileIconBytes(e, t) {
  var o = await hostAppObject.OpenIconCursor("ignoreMe");
  if (o && o.length > 0) {
    readFileToIPictureBytes(e, t, o);
  }
}
async function allowCompilerProcessToSetForegroundWIndow(e) {
  await hostAppObject.AllowCompilerProcessToSetForegroundWIndow("ignoreMe");
  e();
}
async function ideToForeground() {
  await hostAppObject.ideToForeground("ignoreMe");
}
function createFormDesignerGlobals(e, t) {
  e.globalVars = {
    uri: t,
    isDirty: false,
    rootElement: e,
    vscode: {
      postMessage: (t) => {
        if (t.type === "serverConnected") {
          formDesigner_revert(e.globalVars, e.editorNode.formProperties);
        } else if (t.type === "onClickedPreview") {
          allowCompilerProcessToSetForegroundWIndow(() => {
            var o = t.args[0];
            debugSocket.request("onClickedPreview", {
              uri: "twinbasic:" + e.globalVars.uri,
              FormDesignerId: o.form[0].FormDesignerId,
              serializedForm: e.globalVars.isDirty
                ? JSONstringifyOrdered(o.form, "\t")
                : null,
              docVersion: e.editorNode.fileNode.ideVersionId,
            });
          });
        } else if (t.type === "onSignificantChange") {
          var o = t.args[0];
          e.editorNode.fileNode.ideVersionId++;
          debugSocket.request("onSignificantChange", {
            uri: "twinbasic:" + e.globalVars.uri,
            FormDesignerId: o.form[0].FormDesignerId,
            serializedForm: JSONstringifyOrdered(o.form, "\t"),
            docVersion: e.editorNode.fileNode.ideVersionId,
          });
          var n = e.globalVars;
          n.isDirty = true;
          openEditors.updateDirtyState(e.editorNode);
          try {
            updateHistory(e.globalVars.uri, o.form[0].Name);
          } catch (e) {}
        } else if (t.type === "ownerUndo") {
          var n = e.globalVars;
          if (!n.state.prev) return;
          n.state = n.state.prev;
          formDesigner_syncToState(
            e.globalVars,
            n.state.item.form,
            n.state.item.selected,
            n.state.prev !== undefined ? true : false,
            n.state.next !== undefined ? true : false
          );
          n.vscode.postMessage({
            type: "onSignificantChange",
            args: [n.state.item],
          });
          if (!n.state.prev) {
            n.isDirty = false;
            openEditors.updateDirtyState(e.editorNode);
          }
        } else if (t.type === "ownerRedo") {
          var n = e.globalVars;
          if (!n.state.next) return;
          if (!n.state.prev) {
            n.isDirty = true;
            openEditors.updateDirtyState(e.editorNode);
          }
          n.state = n.state.next;
          formDesigner_syncToState(
            e.globalVars,
            n.state.item.form,
            n.state.item.selected,
            n.state.prev !== undefined ? true : false,
            n.state.next !== undefined ? true : false
          );
          n.vscode.postMessage({
            type: "onSignificantChange",
            args: [n.state.item],
          });
        } else if (t.type === "onChanged") {
          var i = t.args[0];
          var n = e.globalVars;
          var r = n.state;
          n.state = { item: i, prev: r };
          r.next = n.state;
          n.vscode.postMessage({ type: "onSignificantChange", args: [i] });
          n.isDirty = true;
          openEditors.updateDirtyState(e.editorNode);
          n.formDesignerId = i.form[0]["FormDesignerId"];
        } else if (t.type === "onChangedSelection") {
          var s = t.args[0];
          var n = e.globalVars;
          n.state.item.selected = s;
        } else if (t.type === "onChangedNoUndo") {
          var i = t.args[0];
          var n = e.globalVars;
          n.state.item.form = i.form;
        } else if (t.type == "getClipboardData") {
          navigator.clipboard
            .readText()
            .then((t) => {
              formDesigner_gotClipboardData(e.globalVars, t);
            })
            .catch((e) => {
              msgBox(
                "错误: 无法读取剪贴板内容: " + e.toString()
              );
            });
        } else if (t.type == "copy") {
          if (e.oncopy) e.oncopy();
        } else if (t.type == "paste") {
          if (e.onpaste) e.onpaste();
        } else if (t.type == "paste2") {
          if (e.onpaste) e.onpaste2();
        } else if (t.type == "cut") {
          if (e.oncut) e.oncut();
        } else if (t.type == "clipboardCopy") {
          var a = t.args[0];
          navigator.clipboard.writeText(a);
        } else if (t.type === "debugMsg") {
          var a = t.args[0];
          msgBox(a.toString());
        } else if (t.type === "debugModalQuestion") {
          var a = t.args[0];
          var l = t.args[1];
          var d = t.args[2];
          var c = createDOMElement(undefined, "div", "simpleMsgBoxNoImage", a);
          showModalDialog(c, [
            {
              caption: "YES",
              onclick: () => {
                hideModalDialog();
                if (l) l();
              },
            },
            {
              caption: "NO",
              onclick: () => {
                hideModalDialog();
                if (d) d();
              },
            },
          ]);
        } else if (t.type === "onChangedFormDesignerConfiguration") {
          var u = t.args[0];
          ideSettings.FORMS.put_leftSidePanelWidth(u.leftSidePanelWidth);
          ideSettings.FORMS.put_rightSidePanelWidth(u.rightSidePanelWidth);
          ideSettings.FORMS.put_windowsPalette(u.windowsPalette);
        } else if (t.type === "viewCode") {
          toggleFormDesign();
        } else if (t.type === "jumpToFile") {
          openEditors.convertPreviewTabToRealTab(e.editorNode);
          var p = t.args[0];
          var f = t.args[1];
          var g = t.args[2];
          var m = t.args[3];
          var h = t.args[4];
          var v = fs.tree.resolvePath("twinbasic:" + p);
          openEditors.openFile(v, false, false, false, f + 1, g + 1);
        } else if (t.type === "insertEvent") {
          openEditors.convertPreviewTabToRealTab(e.editorNode);
          var p = t.args[0];
          var f = t.args[1];
          var g = t.args[2];
          var y = t.args[3];
          var v = fs.tree.resolvePath("twinbasic:" + p);
          openEditors.openFile(
            v,
            false,
            false,
            false,
            f + 1,
            g + 1,
            false,
            () => {
              var e = new monaco.Range(f + 1, g + 1, f + 1, g + 1);
              revealedLineTime = undefined;
              editor.setSelection(e);
              let t = editor.getContribution("snippetController2");
              t.insert(y);
            }
          );
        } else if (t.type === "ensureImageServerIsReady") {
          formDesigner_imageServerReady(
            e.globalVars,
            root.formImageServerPort,
            root.serverID + "/"
          );
        } else if (t.type === "openFilePictureBytes") {
          var b = t.args[0];
          openFilePictureBytes(e.editorNode, b);
        } else if (t.type === "openFileIconBytes") {
          var b = t.args[0];
          openFileIconBytes(e.editorNode, b);
        } else {
          msgBox("来自 postMessage: " + t.type);
        }
      },
    },
    showGrid: true,
    alignToGrid: false,
    alignToGridX: 10,
    alignToGridY: 10,
    showOutlines: false,
    lockedControls: [],
    windowsPalette: "",
    tbDockNone: undefined,
    tbDockTop: undefined,
    tbDockLeft: undefined,
    tbDockBottom: undefined,
    tbDockRight: undefined,
    tbDockFill: undefined,
    WinForms: undefined,
    lastKnownMousePositionX: 0,
    lastKnownMousePositionY: 0,
    testRedBoxImageDataBase64: "",
    CachedIsExpanded: {},
    focusNextRun: undefined,
    ImageRequestId: 0,
    uniqueId: "",
    uniqueFormDesignerId: undefined,
    ImageServerPort: 0,
    customControlsArray: undefined,
    gotInitialFormData: false,
    outstandingSerializationRequests: 0,
    totalSerializationRequests: 0,
    totalCountOfOutOfDateRequests: 0,
    controlRepaintStart: 0,
    activeDropElement: undefined,
    dragDropOriginalElement: undefined,
    exampleSocket: undefined,
    webworker: undefined,
    DisableControlsRepaintBoxes: true,
    ServerID: "",
    contextMenuRevealTimer: undefined,
    IgnoringEscapeKey: false,
    infoIcon: "<div class='infoIcon'></div>",
    setupPropertyEditorFunctions2: [
      setupPropertyEditor2_Unsupported,
      setupPropertyEditor2_Unsupported,
      setupPropertyEditor2_Integer,
      setupPropertyEditor2_Long,
      setupPropertyEditor2_Single,
      setupPropertyEditor2_Double,
      setupPropertyEditor2_Currency,
      setupPropertyEditor2_Date,
      setupPropertyEditor2_String,
      setupPropertyEditor2_Unsupported,
      setupPropertyEditor2_Unsupported,
      setupPropertyEditor2_Boolean,
      setupPropertyEditor2_Unsupported,
      setupPropertyEditor2_Unsupported,
      setupPropertyEditor2_Decimal,
      setupPropertyEditor2_Unsupported,
      setupPropertyEditor2_Unsupported,
      setupPropertyEditor2_Byte,
      setupPropertyEditor2_Unsupported,
      setupPropertyEditor2_Unsupported,
      setupPropertyEditor2_LongLong,
    ],
    body: e.querySelector("body"),
    designerDragPointTopLeft: e.querySelector(".designerDragPointTopLeft"),
    designerDragPointTop: e.querySelector(".designerDragPointTop"),
    designerDragPointTopRight: e.querySelector(".designerDragPointTopRight"),
    designerDragPointLeft: e.querySelector(".designerDragPointLeft"),
    designerDragPointRight: e.querySelector(".designerDragPointRight"),
    designerDragPointBottomLeft: e.querySelector(
      ".designerDragPointBottomLeft"
    ),
    designerDragPointBottom: e.querySelector(".designerDragPointBottom"),
    designerDragPointBottomRight: e.querySelector(
      ".designerDragPointBottomRight"
    ),
    designerContainer: e.querySelector(".designerContainer"),
    designerContainerOUTER: e.querySelector(".designerContainerOUTER"),
    designerDragInfoLeft: e.querySelector(".designerDragInfoLeft"),
    designerDragInfoRight: e.querySelector(".designerDragInfoRight"),
    designerMenuBar: e.querySelector(".designerMenuBar"),
    designer: e.querySelector(".designer"),
    toolBox: e.querySelector(".toolBox"),
    toolBoxInner: e.querySelector(".toolBoxInner"),
    propertySheet: e.querySelector(".propertySheet"),
    controlSelecter: e.querySelector(".controlSelecter"),
    toolbarProperties: e.querySelector(".toolbarProperties"),
    toolbarEvents: e.querySelector(".toolbarEvents"),
    propertiesBox: e.querySelector(".propertiesBox"),
    propertiesBoxInner: e.querySelector(".propertiesBoxInner"),
    proprtiesBoxFooter: e.querySelector(".proprtiesBoxFooter"),
    menuBarTest: e.querySelector(".menuBarTest"),
    menuBarUndo: e.querySelector(".menuBarUndo"),
    menuBarRedo: e.querySelector(".menuBarRedo"),
    menuBarAlignLeft: e.querySelector(".menuBarAlignLeft"),
    menuBarAlignTop: e.querySelector(".menuBarAlignTop"),
    menuBarAlignRight: e.querySelector(".menuBarAlignRight"),
    menuBarAlignBottom: e.querySelector(".menuBarAlignBottom"),
    menuBarSizeWidest: e.querySelector(".menuBarSizeWidest"),
    menuBarSizeTallest: e.querySelector(".menuBarSizeTallest"),
    menuBarSizeNarrowest: e.querySelector(".menuBarSizeNarrowest"),
    menuBarSizeShortest: e.querySelector(".menuBarSizeShortest"),
    menuBarGrid: e.querySelector(".menuBarGrid"),
    menuBarGridOptions: e.querySelector(".menuBarGridOptions"),
    optionGridShow: e.querySelector(".optionGridShow"),
    optionGridSnap: e.querySelector(".optionGridSnap"),
    optionShowOutlines: e.querySelector(".optionShowOutlines"),
    optionGridWidth: e.querySelector(".optionGridWidth"),
    optionGridHeight: e.querySelector(".optionGridHeight"),
    menuBarBringToFront: e.querySelector(".menuBarBringToFront"),
    menuBarSendToBack: e.querySelector(".menuBarSendToBack"),
    zoomSelect: e.querySelector(".zoomSelect"),
    menuBarPreview: e.querySelector(".menuBarPreview"),
    menuBar: e.querySelector(".menuBar"),
    selectionArea: e.querySelector(".selectionArea"),
    selectionAreaDragInfoLeft: e.querySelector(".selectionAreaDragInfoLeft"),
    selectionAreaDragInfoRight: e.querySelector(".selectionAreaDragInfoRight"),
    licenceOverlay: e.querySelector(".licenceOverlay"),
    licenceButton: e.querySelector(".licenceButton"),
    resyncOverlay: e.querySelector(".resyncOverlay"),
    resyncButton: e.querySelector(".resyncButton"),
    contextMenu: e.querySelector(".contextMenu"),
    contextMenu2: e.querySelector(".contextMenu2"),
    contextMenuUnderlay: e.querySelector(".contextMenuUnderlay"),
    loadingOverlay: e.querySelector(".loadingOverlay"),
    loadingOverlayInfo: e.querySelector(".loadingOverlayInfo"),
    loadingOverlayInfoBitmapProgress: e.querySelector(
      ".loadingOverlayInfoBitmapProgress"
    ),
    loadingOverlayIgnoreButton: e.querySelector(".loadingOverlayIgnoreButton"),
    dragPointWidth: e.querySelector(".designerDragPointTopRight").clientWidth,
    dragPointHeight: e.querySelector(".designerDragPointTopRight").clientHeight,
    currentFlashingContainer: undefined,
    allControls: [],
    allToolboxItems: [],
    allMenubarItems: [
      e.querySelector(".menuBarAlignLeft"),
      e.querySelector(".menuBarAlignTop"),
      e.querySelector(".menuBarAlignRight"),
      e.querySelector(".menuBarAlignBottom"),
      e.querySelector(".menuBarSizeWidest"),
      e.querySelector(".menuBarSizeTallest"),
      e.querySelector(".menuBarSizeNarrowest"),
      e.querySelector(".menuBarSizeShortest"),
      e.querySelector(".menuBarBringToFront"),
      e.querySelector(".menuBarSendToBack"),
    ],
    selectedTool: undefined,
    formSelectorOption: undefined,
    CustomControlUniqueId: 2,
    initialHTML: undefined,
    propertyValueEditor: undefined,
    focusedPropertyName: undefined,
    focusedPropertyDiv: undefined,
    selectedControls: [],
    inclusionCountID: 0,
    isDragging: false,
    zoomRatio: 1,
    attemptCount: 0,
    gotClipboardDataFunction: undefined,
    revertCount: 0,
    pendingControlRefreshes: [],
    gp: e.querySelector(".gp"),
    gpOuter: e.querySelector(".gpOuter"),
    gpOK: e.querySelector(".gpOK"),
    gpGranularityValue: e.querySelector(".gpGranularityValue"),
    gpCancel: e.querySelector(".gpCancel"),
    FormDesignerInstanceUniqueId: formDesignerInstanceId++,
    queuedImageRequests: [],
    AutoResyncWhenNextVisible: false,
  };
  dragElement(e.globalVars, e.globalVars.gpOuter);
  var o = {
    leftSidePanelWidth: ideSettings.FORMS.get_leftSidePanelWidth(),
    rightSidePanelWidth: ideSettings.FORMS.get_rightSidePanelWidth(),
    windowsPalette: ideSettings.FORMS.get_windowsPalette(),
  };
  var n = { customControls: lspSocket.latestCustomControls };
  var i = "BLAH";
  var r = "BLAH2";
  formDesigner_init(e.globalVars, o, n.customControls, i, r);
  formDesigner_imageServerReady(
    e.globalVars,
    root.formImageServerPort,
    root.serverID + "/"
  );
}
const fileHandler_tbform = {
  activated(e, t, o, n) {
    e.type = "UIDesigner";
    statusLineCol.classList.add("hide");
    codePanelMainInnerMonacoContainer.classList.add("hide");
    codePanelDropDownContainer.classList.add("hideNotCodeEditor");
    changedSize();
    if (!e.domContainer) {
      this.createFormDesigner(e);
    } else {
      e.domContainer.classList.remove("hide");
      if (e.domContainer.globalVars.AutoResyncWhenNextVisible) {
        e.domContainer.globalVars.AutoResyncWhenNextVisible = false;
        refreshAllControlImages(e.domContainer.globalVars);
        e.domContainer.globalVars.resyncOverlay.style.visibility = "hidden";
      }
      if (
        e.domContainer.globalVars.resyncOverlay.style.visibility == "visible"
      ) {
        e.domContainer.globalVars.resyncButton.innerText = "PLEASE WAIT...";
        e.domContainer.globalVars.resyncButton.onclick();
      }
    }
    e.fileNode.tree.changeSelection(e.fileNode, o, n);
    outlinePanel.syncSymbols([]);
  },
  deactivated(e) {
    e.domContainer.classList.add("hide");
  },
  undo(e) {
    e.domContainer.globalVars.vscode.postMessage({ type: "ownerUndo" });
  },
  redo(e) {
    e.domContainer.globalVars.vscode.postMessage({ type: "ownerRedo" });
  },
  isDirty(e) {
    return e.domContainer.globalVars.isDirty;
  },
  createFormDesigner(e) {
    e.domContainer = createDOMElement(
      codePanelMainInner,
      "div",
      "formDesignerContainer"
    );
    e.domContainer.innerHTML = `\n                    <div class='contextMenuUnderlay'></div>\n                    <div class='contextMenu'></div>\n                    <div class='contextMenu2'></div>\n                    <div class='licenceOverlay'>&#9888; As this feature is experimental, it is currently only available to registered users.<br/><div class='licenceButton'>Enter your licence key</div></div>\n                    <div class='resyncOverlay'>&#9888; RESYNC REQUIRED<br/><div class='resyncButton'>RESYNC</div></div>\n                    <div class='loadingOverlay'><div class='loadingOverlaySpinner'><div class='loadingOverlayInfo'></div><div class='loadingOverlayInfoBitmapProgress'></div><div class='loadingOverlayIgnoreButton'>Ignore and continue</div></div></div>\n                    <div class="gpOuter">\n                        <div class='gp gpGnonDraggable'></div>\n                        <div class='gpGranularity'>\n                            Granularity: <input class='gpGnonDraggable gpGranularityValue' type='number'></input>\n                        </div>\n                        <div class='gpButtons'>\n                            <div class='gpGnonDraggable gpCancel'>Cancel</div>\n                            <div class='gpGnonDraggable gpOK'>OK</div>\n                        </div>\n                    </div>\n\n                    <div class='menuBarGridOptions'>\n                        <div class='menuBarGridOptionsInner'>\n                            <div class='menuBarGridOptionRow'><div class='menuBarGridOption'>显示网格</div><div class='menuBarGridValue'><input class='optionGridShow' type='checkbox'/></div></div>\n                            <div class='menuBarGridOptionRow'><div class='menuBarGridOption'>对齐控件到网格</div><div class='menuBarGridValue'><input class='optionGridSnap' type='checkbox'/></div></div>\n                            <div class='menuBarGridOptionRow'><div class='menuBarGridOption'>显示虚线</div><div class='menuBarGridValue'><input class='optionShowOutlines' type='checkbox'/></div></div>\n                            <div class='menuBarGridOptionRow'><div class='menuBarGridOption'>网格宽度</div><div class='menuBarGridValue'><input class='optionGridWidth' type='number' size="3" min="1"/></div></div>\n                            <div class='menuBarGridOptionRow'><div class='menuBarGridOption'>网格高度</div><div class='menuBarGridValue'><input class='optionGridHeight' type='number' size="3" min="1"/></div></div>\n                        </div>\n                    </div>\n                    \n                    <div class='menuBar'>\n                        <div class='menuBarItem menuBarItemActive menuBarTest' title='Undo'></div>\n                        <div class='menuBarItem menuBarUndo' title='Undo'></div>\n                        <div class='menuBarItem menuBarRedo' title='Redo'></div>\n                        <div class='menuBarSeperator'></div>\n                        <div class='menuBarItem menuBarAlignLeft' title='Align controls to the LEFT'></div>\n                        <div class='menuBarItem menuBarAlignTop' title='Align controls to the TOP'></div>\n                        <div class='menuBarItem menuBarAlignRight' title='Align controls to the RIGHT'></div>\n                        <div class='menuBarItem menuBarAlignBottom' title='Align controls to the BOTTOM'></div>\n                        <div class='menuBarSeperator'></div>\n                        <div class='menuBarItem menuBarSizeWidest' title='Resize controls to the WIDEST'></div>\n                        <div class='menuBarItem menuBarSizeTallest' title='Resize controls to the TALLEST'></div>\n                        <div class='menuBarItem menuBarSizeNarrowest' title='Resize controls to the NARROWEST'></div>\n                        <div class='menuBarItem menuBarSizeShortest' title='Resize controls to the SHORTEST'></div>\n                        <div class='menuBarSeperator'></div>\n                        <div class='menuBarItem menuBarItemActive menuBarToggleOn menuBarGrid' title='Toggle the grid indicators ON/OFF'></div>\n                        <div class='menuBarSeperator'></div>\n                        <div class='menuBarItem menuBarBringToFront' title='Bring the selected control to the FRONT of the z-order'></div>\n                        <div class='menuBarItem menuBarSendToBack' title='Send the selected control to the BACK of the z-order'></div>\n                        <div class='menuBarSeperator'></div>\n                        <div class='menuBarZoom'><select class='zoomSelect'><option value="0.25">25%</option><option value="0.5">50%</option><option value="0.75">75%</option><option value="1" selected>100%</option><option value="1.25">125%</option><option value="1.5">150%</option><option value="1.75">175%</option><option value="2">200%</option><option value="2.25">225%</option><option value="2.5">250%</option><option value="2.75">275%</option><option value="3">300%</option><option value="3.25">325%</option><option value="3.5">350%</option><option value="3.75">375%</option><option value="4">400%</option></select></div>\n                        <div class='menuBarItem menuBarItemActive menuBarPreview'>🡆 预览</div>\n                    </div>\n                    <div class='toolBox'>\n                        <div class='toolBoxInner'>\n                        </div>\n                    </div>\n                    <div class='propertiesBox'>\n                        <div class='propertiesBoxInner'>\n                            <div class='titleBar'><div class='selected toolbarProperties'>属性</div><div class='toolbarEvents'>事件</div></div>\n                            <div class='proertiesBoxContent'>\n                                <div class='controlSelecterOuter'>\n                                    <select class="controlSelecter">\n                                    <option hidden disabled selected value></option>\n                                    <option hidden disabled selected value>[MULTI-SELECT]</option>\n                                    </select>\n                                </div>\n                                <div class='propertySheet'>\n                                </div>\n                            </div>\n                        </div>\n                        <div class='proprtiesBoxFooter'>\n                        </div>\n                    </div>\n                    \n                    <div class='designerContainerOUTER'>\n                        <div class='designerMenuBar'></div>\n                        <div class='designerContainer'>\n                            <div id='lineOuter'><div id='line'></div></div>\n                            <div class='designer'></div>\n                            <div class='designerDragPointInactive designerDragPointTopLeft'></div>\n                            <div class='designerDragPointInactive designerDragPointTop'></div>\n                            <div class='designerDragPointInactive designerDragPointTopRight'></div>\n                            <div class='designerDragPointInactive designerDragPointLeft'></div>\n                            <div class='designerDragPoint designerDragPointRight'></div>\n                            <div class='designerDragPoint designerDragPointBottom'></div>\n                            <div class='designerDragPointInactive designerDragPointBottomLeft'></div>\n                            <div class='designerDragPoint designerDragPointBottomRight'></div>\n                            <div class='designerDragInfoLeft designerDragInfoLeft'></div>\n                            <div class='designerDragInfoRight designerDragInfoRight'></div>\n                            <div class='selectionAreaDragInfoRight'></div>\n                            <div class='selectionAreaDragInfoLeft'></div>\n                            <div class='selectionArea'></div>\n                        </div>\n                    </div>\n                    `;
    e.domContainer.editorNode = e;
    e.domContainer.tabIndex = "0";
    createFormDesignerGlobals(e.domContainer, e.fileNode.getFullPath());
    e.domContainer.globalVars.state = {
      item: { form: e.formProperties },
      prev: undefined,
    };
    e.domContainer.onundo = () => {
      debugger;
      e.domContainer.globalVars.vscode.postMessage({ type: "ownerUndo" });
    };
    e.domContainer.onredo = () => {
      debugger;
      e.domContainer.globalVars.vscode.postMessage({ type: "ownerRedo" });
    };
  },
  save(e, t) {
    const o = JSONstringifyOrdered(
      e.domContainer.globalVars.state.item.form,
      "\t"
    );
    const n = new TextEncoder();
    var i = n.encode(o);
    e.fileNode.lastSaved_ideVersionId = e.fileNode.ideVersionId;
    e.domObject_CloseButton.className = "progressSpinnerIcon";
    fs.writeFile(e.fileNode, i, e.fileNode.ideVersionId, 0, (o) => {
      e.domObject_CloseButton.className = "tabItemIconRight";
      if (o !== 0) return;
      e.domContainer.globalVars.isDirty = false;
      openEditors.updateDirtyState(e);
      if (t) t();
    });
  },
  resyncToFileSystem(e) {
    formDesigner_imageServerReady(
      e.domContainer.globalVars,
      root.formImageServerPort,
      root.serverID + "/"
    );
    var t = e.fileNode.getFullPath();
    e.domContainer.globalVars.uri = t;
    var o = fs.tree.resolvePath("twinbasic:" + t);
    if (o) {
      e.fileNode = o;
      o.openEditorNode = e;
      if (openEditors.isDirtyEditor(e)) {
        var n = e.domContainer.globalVars;
        n.vscode.postMessage({
          type: "onSignificantChange",
          args: [n.state.item],
        });
      } else {
      }
    } else {
      const o = JSONstringifyOrdered(
        e.domContainer.globalVars.state.item.form,
        "\t"
      );
      fs.createFileUTF8(t, o, () => {
        var o = fs.tree.resolvePath("twinbasic:" + t);
        e.fileNode = o;
        o.openEditorNode = e;
      });
    }
  },
  closing(e, t, o) {
    if (t) {
      this.save(e, o);
    } else {
      var n = "twinbasic:" + e.fileNode.getFullPath();
      lspSocket.event("textDocument/didClose", {
        textDocument: { uri: n },
        docVersion: e.fileNode.ideVersionId,
      });
      e.fileNode.lastSaved_ideVersionId = e.fileNode.ideVersionId;
      o();
    }
  },
  closed(e) {
    codePanelMainInner.removeChild(e.domContainer);
    delete e.domContainer.globalVars;
    delete e.domContainer.editorNode;
  },
  onFocus(e) {
    e.domContainer.focus();
  },
  onReveal(e, t, o, n) {},
  gotFileData(e, t) {
    var o = new TextDecoder().decode(t);
    try {
      e.formProperties = JSON.parse(o);
      if (
        e.formProperties[0]["FormDesignerId"] === undefined ||
        e.formProperties[0]["FormDesignerId"] === null
      ) {
        e.formProperties[0]["FormDesignerId"] = generateUUID();
      }
    } catch {
      msgBox("错误: 解析tbform时遇到错误的JSON");
    }
    openEditors.changeSelectedEditor(
      e,
      e.initialOptions.preview,
      e.initialOptions.ctrlKey,
      e.initialOptions.shiftKey
    );
  },
};
const fileHandler_text = {
  activated(e, t, o, n) {
    e.type = "TextEditor";
    clearEditor();
    editor.updateOptions({ glyphMargin: false, readOnly: e.fileNode.readOnly });
    editor.setModel(e.monacoModelInstance);
    let i = e.fileNode.name.split(".").pop().toLowerCase();
    if (i === "js") {
      monaco.editor.setModelLanguage(e.monacoModelInstance, "javascript");
    } else if (i === "ts") {
      monaco.editor.setModelLanguage(e.monacoModelInstance, "typescript");
    } else if (i === "html" || i === "htm") {
      monaco.editor.setModelLanguage(e.monacoModelInstance, "html");
    } else if (i === "css" || i === "json" || i === "xml" || i === "ini") {
      monaco.editor.setModelLanguage(e.monacoModelInstance, i);
    } else if (i === "md") {
      monaco.editor.setModelLanguage(e.monacoModelInstance, "markdown");
    } else {
      monaco.editor.setModelLanguage(e.monacoModelInstance, "plaintext");
    }
    lineNum.innerText = 1;
    columnNum.innerText = 1;
    if (e.monacoViewState) {
      editor.restoreViewState(e.monacoViewState);
    }
    statusLineCol.classList.remove("hide");
    codePanelMainInnerMonacoContainer.classList.remove("hide");
    codePanelDropDownContainer.classList.add("hideNotCodeEditor");
    changedSize();
    if (!t) editor.focus();
    e.fileNode.tree.changeSelection(e.fileNode, o, n);
  },
  deactivated(e) {
    e.monacoViewState = editor.saveViewState();
  },
  undo(e) {
    editor.getModel().undo();
    editor.focus();
  },
  redo(e) {
    editor.getModel().redo();
    editor.focus();
  },
  isDirty(e) {
    if (!e.monacoModelInstance) return false;
    return (
      e.openingAltVersionId !== e.monacoModelInstance.getAlternativeVersionId()
    );
  },
  save(e, t) {
    var o = e.fileNode.openEditorNode.monacoModelInstance.getValue();
    e.fileNode.lastSaved_ideVersionId = e.fileNode.ideVersionId;
    e.domObject_CloseButton.className = "progressSpinnerIcon";
    fs.writeFile(
      e.fileNode,
      o,
      e.fileNode.ideVersionId,
      e.isSystemANSIFile ? 1 : 0,
      (o) => {
        e.domObject_CloseButton.className = "tabItemIconRight";
        if (o !== 0) return;
        e.openingAltVersionId = e.monacoModelInstance.getAlternativeVersionId();
        openEditors.updateDirtyState(e);
        if (t) t();
      }
    );
  },
  resyncToFileSystem(e) {
    var t = e.fileNode.getFullPath();
    var o = fs.tree.resolvePath("twinbasic:" + t);
    if (o) {
      e.fileNode = o;
      o.openEditorNode = e;
      if (openEditors.isDirtyEditor(e)) {
        var n = { versionId: e.monacoModelInstance.getVersionId() };
        e.monacoModelInstance.ourChangeContentHandler(n);
      } else {
        openEditors.syncEditorToFileSystem(o);
      }
    } else {
      fs.createFileUTF8(t, "", () => {
        var o = fs.tree.resolvePath("twinbasic:" + t);
        e.fileNode = o;
        o.openEditorNode = e;
        var n = { versionId: e.monacoModelInstance.getVersionId() };
        e.monacoModelInstance.ourChangeContentHandler(n);
      });
    }
  },
  closing(e, t, o) {
    if (t) {
      this.save(e, o);
    } else {
      var n = "twinbasic:" + e.fileNode.getFullPath();
      e.fileNode.ideVersionId++;
      e.fileNode.lastSaved_ideVersionId = e.fileNode.ideVersionId;
      lspSocket.event("textDocument/didClose", {
        textDocument: { uri: n },
        docVersion: e.fileNode.lastSaved_ideVersionId,
      });
      o();
    }
  },
  closed(e) {},
  onFocus(e) {
    editor.focus();
  },
  onReveal(e, t, o, n) {
    revealLineInEditor(t, o, n);
  },
  gotFileData(e, t) {
    var o = new TextDecoder().decode(t);
    if (e.monacoModelInstance) {
      e.dontFireContentChanged = true;
      e.monacoModelInstance.setValue(o);
      e.dontFireContentChanged = false;
      e.openingAltVersionId = e.monacoModelInstance.getAlternativeVersionId();
      openEditors.updateDirtyState(e);
      return;
    }
    e.monacoModelInstance = monaco.editor.createModel("", "twinbasic");
    if (liveIDEOptions["tabSize"])
      e.monacoModelInstance.updateOptions({
        tabSize: liveIDEOptions["tabSize"],
      });
    e.monacoModelInstance.cachedBreakpointLines = [];
    e.monacoModelInstance.setValue(o);
    e.openingAltVersionId = e.monacoModelInstance.getAlternativeVersionId();
    e.monacoModelInstance.ourChangeContentHandler = (t) => {
      if (e.dontFireContentChanged) return;
      e.fileNode.ideVersionId = e.fileNode.lastSaved_ideVersionId + t.versionId;
      openEditors.updateDirtyState(e);
      var o = "twinbasic:" + e.fileNode.getFullPath();
      var n = e.monacoModelInstance.getValue();
      var i = [];
      lspSocket.event("textDocument/didChange", {
        textDocument: { uri: o, version: e.fileNode.ideVersionId },
        contentChanges: [{ text: n }],
        simpleBreakpoints: breakpointsChanged ? i : undefined,
        enterKeyAtLine: enterKeyAtLine,
      });
    };
    e.monacoModelInstance.onDidChangeContent(
      e.monacoModelInstance.ourChangeContentHandler
    );
    openEditors.changeSelectedEditor(
      e,
      e.initialOptions.preview,
      e.initialOptions.ctrlKey,
      e.initialOptions.shiftKey
    );
    if (e.initialOptions.line)
      revealLineInEditor(
        e.initialOptions.line,
        e.initialOptions.column,
        e.initialOptions.viewPortTop
      );
  },
};
const showNewProjects = 1;
const showRecentProjects = 2;
var g_ShowNewProjectOptions = false;
var g_IsLoadingVBP = false;
var BuiltInProjects = [
  { name: "Standard EXE", projectPath: "$\\_Standard EXE" },
  { name: "ActiveX DLL", projectPath: "$\\_ActiveX DLL" },
  { name: "Import...", projectPath: "$" },
];
var SampleProjects = [{ name: "Sample 1. ", projectPath: "$\\ABC.twinproj" }];
var RecentProjects = [{ name: "Sample X. ", projectPath: "$\\ABC.twinproj" }];
function listviewFromArray(e, t) {
  e.innerHTML = "";
  var o = undefined;
  t.forEach((t) => {
    var n = t.name;
    var i = "";
    var r = t.name.indexOf("#");
    if (r !== -1) {
      n = t.name.substring(0, r);
      i = t.name.substring(r + 1);
    }
    var s = createDOMElement(e, "div", "frontPageListViewItem", n);
    if (i.length) {
      var a = createDOMElement(s, "div", "frontPageListViewItemSubText", i);
    }
    s.onclick = () => {
      o.classList.remove("frontPageListViewItemSelected");
      o = s;
      o.classList.add("frontPageListViewItemSelected");
      e.selectedFrontPageItem = t;
    };
    s.ondblclick = () => {
      frontPageOpenProject(t);
    };
    if (!o) {
      o = s;
      o.classList.add("frontPageListViewItemSelected");
      e.selectedFrontPageItem = t;
    }
  });
}
function frontPageOpenProject(e) {
  if (e.projectPath == "$") {
    openProjectVBP();
    hideModalDialog();
  } else if (e.projectPath == "$$") {
    openProjectFromFolder();
    hideModalDialog();
  } else if (e.projectPath.substr(0, 2) == "$\\") {
    HostGetProjectData(e.projectPath.substr(2), (e) => {
      hideModalDialog();
      g_ShowNewProjectOptions = true;
      root.loadProjectFromMemory(e);
    });
  } else {
    hideModalDialog();
    root.loadProject(e.projectPath);
  }
}
async function HostGetProjectsList(e) {
  var t = [];
  hostAppObject_projectsList.forEach((e) => {
    if (e.length > 0) {
      var o = e;
      if (o.substr(0, 1) === "_") o = o.substr(1);
      t.push({ name: o, projectPath: "$\\" + e });
    }
  });
  t.sort((e, t) => {
    if (e.name === "Standard EXE") return -99999;
    return e.name < t.name;
  });
  t.push({ name: "Import from VBP...", projectPath: "$" });
  t.push({ name: "Import from folder...", projectPath: "$$" });
  e.classList.remove("frontPageListViewLIST");
  listviewFromArray(e, t);
}
async function HostGetSamplesList(e) {
  var t = [];
  hostAppObject_samplesList.forEach((e) => {
    if (e.length > 0) {
      t.push({ name: e, projectPath: "$\\" + e });
    }
  });
  t.sort((e, t) => {
    var o = e.name.replace("Sample ", "");
    if (parseInt(o) >= 10) o = "X" + o;
    var n = t.name.replace("Sample ", "");
    if (parseInt(n) >= 10) n = "X" + n;
    return "Sample " + o < "Sample " + n ? -1 : 1;
  });
  e.classList.add("frontPageListViewLIST");
  listviewFromArray(e, t);
}
async function HostGetRecentsList(e) {
  var t = [];
  hostAppObject_recentsList = (
    await hostAppObject.GetRecentsList("ignoreMe")
  ).split("?");
  hostAppObject_recentsList.forEach((e) => {
    if (e.length > 0) {
      t.push({ name: e, projectPath: e });
    }
  });
  e.classList.add("frontPageListViewLIST");
  listviewFromArray(e, t);
}
async function HostReadFileData(e, t) {
  var o = await hostAppObject.ReadFileData(e);
  if (Array.isArray(o)) {
    t(new Uint8Array(o));
  } else {
    alert("内部错误; 无法读取文件数据");
  }
}
async function HostGetProjectData(e, t) {
  var o = await hostAppObject.GetProjectData(e);
  if (Array.isArray(o)) {
    bufferToBase64Async(new Uint8Array(o), (e) => {
      t(e);
    });
  } else {
    alert("内部错误; 无法加载示例项目");
  }
}
function prepareToStart() {
  changedIdeOptions();
  document.getElementById("root").classList.remove("invisible");
  document.getElementById("bannerBackdrop").classList.add("hide");
}
function showFrontPageDialog(e) {
  var t = createDOMElement(undefined, "div", "simpleMsgBoxNoImage", "");
  var o = createDOMElement(t, "div", "frontPageXButton", tbVersionInfo);
  o.title = "";
  var n = createDOMElement(t, "div", "twinBASIClogo logoHeader");
  var i = createDOMElement(t, "div", "buttonGroup");
  var r = createDOMElement(
    i,
    "div",
    "buttonGroupItem buttonGroupItemSelected",
    "新建"
  );
  var s = createDOMElement(i, "div", "buttonGroupItem", "示例");
  var a = createDOMElement(i, "div", "buttonGroupItem", "最近");
  var l = createDOMElement(t, "div", "frontPageListView");
  r.onclick = () => {
    r.classList.add("buttonGroupItemSelected");
    s.classList.remove("buttonGroupItemSelected");
    a.classList.remove("buttonGroupItemSelected");
    HostGetProjectsList(l);
  };
  s.onclick = () => {
    r.classList.remove("buttonGroupItemSelected");
    s.classList.add("buttonGroupItemSelected");
    a.classList.remove("buttonGroupItemSelected");
    HostGetSamplesList(l);
  };
  a.onclick = () => {
    r.classList.remove("buttonGroupItemSelected");
    s.classList.remove("buttonGroupItemSelected");
    a.classList.add("buttonGroupItemSelected");
    HostGetRecentsList(l);
  };
  r.onclick();
  showModalDialog(
    t,
    [
      {
        caption: "浏览...",
        onclick: () => {
          openProject();
          hideModalDialog();
        },
        width: 100,
      },
      {},
      {
        caption: "打开",
        onclick: () => {
          frontPageOpenProject(l.selectedFrontPageItem);
        },
        width: 100,
      },
      {
        caption: "取消",
        onclick: hideModalDialog,
        width: 100,
        isDefaultCancelAction: true,
      },
    ],
    "新建/打开项目...",
    () => {
      hideModalDialog();
    }
  );
  if (e === showNewProjects) {
  } else if (e === showRecentProjects) {
    a.click();
  } else {
    if (liveIDEOptions["showRecentlyOpenedTabFirst"]) {
      a.click();
    }
  }
}
var liveIDEOptions = {};
var licenceKey = undefined;
var codeHintsVisibility = -1;
var ideOptionsSchema = [
  { name: "tabSize", desc: "Tab 尺寸(空格数量)", type: "INTEGER", default: 4 },
  {
    name: "fontSize",
    desc: "IDE 字体大小",
    type: "DROPDOWN",
    options: [
      "8px",
      "9px",
      "10px",
      "11px",
      "12px",
      "13px",
      "14px",
      "15px",
      "16px",
      "17px",
      "18px",
      "19px",
      "20px",
      "21px",
      "22px",
      "23px",
      "24px",
      "25px",
      "26px",
      "27px",
      "28px",
      "29px",
      "30px",
    ],
    default: "13px",
  },
  { name: "fontFamily", desc: "IDE 字体", type: "FONT", default: "Segoe UI" },
  {
    name: "codeFontSize",
    desc: "代码编辑器字体大小",
    type: "DROPDOWN",
    options: [
      "8px",
      "9px",
      "10px",
      "11px",
      "12px",
      "13px",
      "14px",
      "15px",
      "16px",
      "17px",
      "18px",
      "19px",
      "20px",
      "21px",
      "22px",
      "23px",
      "24px",
      "25px",
      "26px",
      "27px",
      "28px",
      "29px",
      "30px",
    ],
    default: "13px",
  },
  {
    name: "codeFontFamily",
    desc: "代码编辑器字体",
    type: "FONT",
    default: "Monaco",
  },
  {
    name: "colorTheme",
    desc: "配色主题",
    type: "DROPDOWN",
    options: ["dark", "light"],
    default: "dark",
  },
  {
    name: "f8keyMode",
    desc: "F8 键行为",
    type: "DROPDOWN",
    options: ["debug", "error-cycling"],
    default: "debug",
  },
  {
    name: "showCodeDropDowns",
    desc: "显示代码编辑器组合选择器",
    type: "DROPDOWN",
    options: ["above", "below", "none"],
    default: "above",
  },
  {
    name: "monaco.renderWhitespace",
    desc: "Monaco: 渲染空白",
    type: "DROPDOWN",
    options: ["all", "none", "boundary", "selection", "trailing"],
    default: "none",
  },
  {
    name: "monaco.renderIndentGuides",
    desc: "Monaco: 渲染缩进指示",
    type: "CHECKBOX",
    default: false,
  },
  {
    name: "monaco.showMinimap",
    desc: "Monaco: 显示小地图",
    type: "CHECKBOX",
    default: false,
  },
  {
    name: "monaco.showFoldingControls",
    desc: "Monaco: 显示折叠控件",
    type: "DROPDOWN",
    options: ["always", "mouseover"],
    default: "mouseover",
  },
  {
    name: "64bitMode",
    desc: "编译器: 启动64位模式",
    type: "CHECKBOX",
    default: false,
  },
  {
    name: "preserveCodeEditorStateOnReopen",
    desc: "打开项目时恢复编辑器状态",
    type: "CHECKBOX",
    default: true,
  },
  {
    name: "showRecentlyOpenedTabFirst",
    desc: "IDE 启动时聚焦“最近的”标签",
    type: "CHECKBOX",
    default: false,
  },
  {
    name: "askBeforeDeleteFiles",
    desc: "文件管理器: 删除文件前询问",
    type: "CHECKBOX",
    default: true,
  },
  {
    name: "previewDocs",
    desc: "文件管理器: 单击预览",
    type: "CHECKBOX",
    default: false,
  },
  {
    name: "ideDataExecutionPrevention",
    desc: "IDE: 数据执行保护(DEP)",
    type: "CHECKBOX",
    default: true,
  },
  {
    name: "ideLargeAddressAware",
    desc: "IDE: 大地址感知(LAA编译器)",
    type: "CHECKBOX",
    default: false,
  },
  {
    name: "showAdvancedHoverInfo",
    desc: "IDE: 悬停时显示高级信息",
    type: "CHECKBOX",
    default: false,
  },
  {
    name: "showHiddenMembers",
    desc: "IDE: 显示隐藏成员",
    type: "CHECKBOX",
    default: false,
  },
  {
    name: "useHandlesImplementsSyntax",
    desc: "IDE: 使用新的句柄/实现语法",
    type: "CHECKBOX",
    default: false,
  },
  {
    name: "stickyScrolling",
    desc: "IDE: 代码编辑器中的粘性滚动",
    type: "CHECKBOX",
    default: false,
  },
  {
    name: "bracketPairColorization",
    desc: "IDE: 代码编辑器中的括号对颜色化",
    type: "CHECKBOX",
    default: false,
  },
  {
    name: "lessTransparentInvisibleControls",
    desc: "IDE: 对隐藏控件降低透明度",
    type: "CHECKBOX",
    default: false,
  },
  {
    name: "showToolboxIconsOnly",
    desc: "IDE: 只显示工具箱图标",
    type: "CHECKBOX",
    default: true,
  },
  {
    name: "showDebuggerMemUsage",
    desc: "IDE: 显示内存和资源使用情况",
    type: "CHECKBOX",
    default: false,
  },
  {
    name: "codeHintsVisibility",
    desc: "显示IDE内联代码提示",
    type: "DROPDOWN",
    options: ["when CTRL is pressed", "always", "never"],
    default: "when CTRL is pressed",
  },
  {
    name: "intellisenseMode",
    desc: "IDE: 代码提示模式",
    type: "DROPDOWN",
    options: ["LEGACY", "MODERN", "MANUAL"],
    default: "MODERN",
  },
];
function changedIdeOptions() {
  document.getElementById("cssTheme").href =
    "styles-" + "twinbasic-" + liveIDEOptions["colorTheme"] + ".css";
  editor.updateOptions({
    language: "twinbasic",
    theme: "twinbasic-" + liveIDEOptions["colorTheme"],
    renderIndentGuides: liveIDEOptions["monaco.renderIndentGuides"],
    minimap: { enabled: liveIDEOptions["monaco.showMinimap"] },
    showFoldingControls: liveIDEOptions["monaco.showFoldingControls"],
    renderWhitespace: liveIDEOptions["monaco.renderWhitespace"],
    stickyScroll: { enabled: liveIDEOptions["stickyScrolling"] },
    "bracketPairColorization.enabled":
      liveIDEOptions["bracketPairColorization"],
  });
  if (liveIDEOptions["tabSize"]) {
    try {
      editor.getModel().updateOptions({ tabSize: liveIDEOptions["tabSize"] });
    } catch (e) {}
  }
  realCompletionProvider = undefined;
  if (liveIDEOptions["f8keyMode"] === "debug") {
    editor._standaloneKeybindingService.addDynamicKeybinding(
      "-editor.action.marker.nextInFiles",
      null,
      () => {}
    );
  }
  editor._standaloneKeybindingService.addDynamicKeybinding(
    "-editor.action.gotoLine",
    null,
    () => {}
  );
  editor.addCommand(monaco.KeyMod.CtrlCmd | monaco.KeyCode.KeyK, () => {
    commentIcon.click();
  });
  editor.addCommand(
    monaco.KeyMod.Shift | monaco.KeyMod.CtrlCmd | monaco.KeyCode.KeyK,
    () => {
      uncommentIcon.click();
    }
  );
  switch (liveIDEOptions["showCodeDropDowns"]) {
    case "above":
      codePanelDropDownContainer.classList.remove("hide");
      codePanelDropDownContainer.parentElement.insertBefore(
        codePanelDropDownContainer,
        codePanelMain
      );
      break;
    case "below":
      codePanelDropDownContainer.classList.remove("hide");
      codePanelDropDownContainer.parentElement.insertBefore(
        codePanelDropDownContainer,
        null
      );
      break;
    case "none":
      codePanelDropDownContainer.classList.add("hide");
      break;
  }
  if (liveIDEOptions["64bitMode"]) {
    if (buildConfigSelector.value !== "win64") {
      buildConfigSelector.value = "win64";
      buildConfigSelector.onchange();
    }
  }
  var e = liveIDEOptions["fontSize"];
  var t = liveIDEOptions["codeFontSize"];
  var o = liveIDEOptions["fontFamily"];
  if (o.includes("'")) o = "";
  if (!o || o.length == 0) {
    o = "Segoe UI";
  }
  document.body.style.fontFamily = "'" + o + "','Segoe UI', sans-serif";
  var n = liveIDEOptions["codeFontFamily"];
  if (n.includes("'")) n = "";
  if (!n || n.length == 0) {
    n = "Monaco";
  }
  editor.updateOptions({ fontFamily: n });
  editor.updateOptions({ fontSize: t });
  generalScaling = parseInt(e) / 13;
  document.documentElement.style.setProperty("--ide-fontsize", e);
  document.documentElement.style.setProperty("--monaco-fontsize", t);
  document.documentElement.style.setProperty(
    "--generalScaling",
    generalScaling
  );
  changedSize();
  var i = false;
  if (
    lastCompilerStart_ideDataExecutionPrevention !== undefined &&
    lastCompilerStart_ideDataExecutionPrevention !==
      liveIDEOptions["ideDataExecutionPrevention"]
  ) {
    i = true;
  }
  if (
    lastCompilerStart_ideLargeAddressAware !== undefined &&
    lastCompilerStart_ideLargeAddressAware !==
      liveIDEOptions["ideLargeAddressAware"]
  ) {
    i = true;
  }
  if (
    lastCompilerStart_showAdvancedHoverInfo !== undefined &&
    lastCompilerStart_showAdvancedHoverInfo !==
      liveIDEOptions["showAdvancedHoverInfo"]
  ) {
    i = true;
  }
  if (
    lastCompilerStart_showHiddenMembers !== undefined &&
    lastCompilerStart_showHiddenMembers !== liveIDEOptions["showHiddenMembers"]
  ) {
    i = true;
  }
  if (
    lastCompilerStart_useHandlesImplementsSyntax !== undefined &&
    lastCompilerStart_useHandlesImplementsSyntax !==
      liveIDEOptions["useHandlesImplementsSyntax"]
  ) {
    i = true;
  }
  if (
    lastCompilerStart_showDebuggerMemUsage !== undefined &&
    lastCompilerStart_showDebuggerMemUsage !==
      liveIDEOptions["showDebuggerMemUsage"]
  ) {
    restartCompilerSafely();
  }
  if (i) {
    restartCompilerSafely();
  }
  syncCodeHintsVisibility();
}
async function loadIDEOptions(e) {
  var t = false;
  liveIDEOptions = parseJson(await hostAppObject.GetIDESetting("GENERAL"));
  if (!liveIDEOptions) {
    liveIDEOptions = {};
    t = true;
  }
  if (liveIDEOptions["codeFontSize"] === undefined) {
    liveIDEOptions["codeFontSize"] = liveIDEOptions["fontSize"];
  }
  ideOptionsSchema.forEach((e) => {
    if (liveIDEOptions[e.name] === undefined) {
      liveIDEOptions[e.name] = e.default;
    }
  });
  if (t) {
    showIDEOptions(e);
    document.getElementById("CLOSEBTN").classList.add("hide");
    document.getElementById("SAVEBTN").classList.remove("disabled");
  } else {
    e();
  }
  licenceKey = await hostAppObject.GetIDESetting("LicenceKey");
  syncCodeHintsVisibility();
}
function syncCodeHintsVisibility() {
  var e = document.querySelector(":root");
  e.style.setProperty("--inlineDecorationsDisplay", "none");
  if (liveIDEOptions["codeHintsVisibility"] === "always") {
    codeHintsVisibility = 1;
    e.style.setProperty("--inlineDecorationsDisplay", "inline-block");
  } else if (liveIDEOptions["codeHintsVisibility"] === "never") {
    codeHintsVisibility = 0;
  } else {
    codeHintsVisibility = -1;
  }
}
async function saveIDEOptions() {
  await hostAppObject.SaveIDESetting(
    "GENERAL",
    JSON.stringify(liveIDEOptions, undefined, "\t")
  );
}
function changeLicenceKey(e) {
  e = e.trim();
  if (e.length !== 32) e = "00000000000000000000000000000000";
  debugSocket.request("k", { k: e });
}
function onChangeLicence() {
  hideModalDialog();
  var e = createDOMElement(
    undefined,
    "div",
    "simpleMsgBoxNoImage",
    "Enter Licence Key:"
  );
  var t = createDOMElement(e, "input", "searchInputBox");
  var o = createDOMElement(
    e,
    "div",
    "",
    "\nTip: copy and paste the key from your confirmation email.  If you enter\nan invalid key, the COMMUNITY licence will be applied."
  );
  t.onkeydown = (e) => {
    if (e.key === "Escape") {
      hideModalDialog();
    } else if (e.key === "Enter") {
      if (t.value.length > 0) changeLicenceKey(t.value);
      hideModalDialog();
    }
  };
  showModalDialog(e, [
    {
      caption: "购买许可证",
      onclick: () => {
        root.Shell(
          'cmd.exe /c start "link" "https://twinbasic.com/preorder.html"'
        );
        hideModalDialog();
      },
    },
    {},
    {
      caption: "确定",
      onclick: () => {
        if (t.value.length > 0) changeLicenceKey(t.value);
        hideModalDialog();
      },
    },
    { caption: "取消", onclick: hideModalDialog },
  ]);
  t.focus();
  t.select();
}
function showIDEOptions(e) {
  var t = createDOMElement(
    undefined,
    "div",
    "simpleMsgBoxNoImage ideOptionsDialog"
  );
  var o = JSON.parse(JSON.stringify(liveIDEOptions, undefined, "\t"));
  var n = (e) => o[e.name];
  var i = (e, t) => {
    o[e.name] = t;
    if (
      JSON.stringify(o, undefined, "\t") ===
      JSON.stringify(liveIDEOptions, undefined, "\t")
    ) {
      document.getElementById("SAVEBTN").classList.add("disabled");
    } else {
      document.getElementById("SAVEBTN").classList.remove("disabled");
    }
  };
  var r = () => {
    liveIDEOptions = o;
    saveIDEOptions();
    changedIdeOptions();
    hideModalDialog();
    e();
  };
  ideOptionsSchema.forEach((e) => {
    var o = createDOMElement(t, "div", "IDEoption");
    var r = createDOMElement(o, "div", "IDEoptionHeader", e.desc);
    var s = createDOMElement(o, "div", "IDEoptionValue");
    if (e.type === "SHORTTEXT") {
      let t = createDOMElement(s, "input", "IDEoptionShortInput");
      t.value = n(e);
      t.onchange = () => {
        i(e, t.value);
      };
      t.onkeyup = () => {
        i(e, t.value);
      };
    } else if (e.type === "CHECKBOX") {
      let t = createDOMElement(s, "input", "IDEoptionCheckbox");
      t.type = "checkbox";
      t.checked = n(e);
      t.onchange = () => {
        i(e, t.checked);
      };
    } else if (e.type === "DROPDOWN") {
      let t = createDOMElement(s, "select", "IDEoptionDropdown");
      t.onchange = () => {
        i(e, t.value);
      };
      e.options.forEach((e) => {
        var o = createDOMElement(
          undefined,
          "option",
          "IDEoptionDropdownOption",
          e
        );
        o.value = e;
        t.appendChild(o);
      });
      t.value = n(e);
    } else if (e.type === "FONT") {
      let t = createDOMElement(s, "select", "IDEoptionDropdown");
      t.onchange = () => {
        i(e, t.value);
      };
      var a = null;
      GlobalFontsList.forEach((e) => {
        var o = createDOMElement(
          undefined,
          "option",
          "IDEoptionDropdownOption",
          e
        );
        o.value = e;
        t.insertBefore(o, a);
        a = o;
      });
      t.value = n(e);
    } else if (e.type === "INTEGER") {
      let t = createDOMElement(s, "input", "IDEoptionNumeric");
      t.type = "number";
      t.value = n(e);
      t.onchange = () => {
        i(e, t.value);
      };
      t.onkeyup = () => {
        i(e, t.value);
      };
    }
  });
  showModalDialog(
    t,
    [
      {
        id: "LICENCEBTN",
        caption: "更改许可...",
        onclick: onChangeLicence,
        hidden: !projectIsLoaded,
      },
      {},
      { id: "SAVEBTN", caption: "保存更改", onclick: r },
      {
        id: "CLOSEBTN",
        caption: "关闭",
        onclick: () => {
          hideModalDialog();
          e();
        },
        isDefaultCancelAction: true,
      },
    ],
    "twinBASIC IDE 选项"
  );
  document.getElementById("SAVEBTN").classList.add("disabled");
}
function showNewProjectOptions(e, t, o) {
  var n = createDOMElement(
    undefined,
    "div",
    "simpleMsgBoxNoImage ideOptionsDialog"
  );
  var i;
  var r;
  var s;
  var a;
  var l;
  var d;
  var c = e["project.references"].find(
    (e) => e.id === "{F50B82D0-DCAB-43FE-9631-11959D4A4728}"
  );
  var u = t & 1 ? true : false;
  {
    let t = createDOMElement(n, "div", "IDEoption");
    let o = createDOMElement(
      t,
      "div",
      "IDEoptionHeader ProjectoptionHeader",
      "项目名称"
    );
    let r = createDOMElement(t, "div", "IDEoptionValue");
    let s = createDOMElement(r, "input", "IDEoptionMediumInput");
    s.value = "MyProject";
    if (e["project.name"]) s.value = e["project.name"];
    s.onkeydown = (e) => {
      let t = e.key;
      var o = /[ `!@#$£%^&*()+\-=\[\]{};':"\\|,.<>\/?~]/;
      if (o.test(t)) return false;
      return true;
    };
    s.onkeyup = (e) => {
      if (s.value.indexOf("_") == 0) {
        s.value = s.value.substr(1);
      }
    };
    i = s;
  }
  {
    let e = createDOMElement(n, "div", "IDEoption");
    e.title =
      "Option Explicit:\n\n当此项目选项为ON时，编译器将始终在编译代码时进入“Option Explicit”模式，无论您是否在每个模块或类顶部指定“Option Explicit”。\n\n强烈建议您将此项目设置保持为ON。";
    let t = createDOMElement(
      e,
      "div",
      "IDEoptionHeader ProjectoptionHeader",
      "打开强制变量申明"
    );
    let o = createDOMElement(t, "div", "IDEoptionSubHeader", "(项目范围)");
    let i = createDOMElement(e, "div", "IDEoptionValue");
    let s = createDOMElement(i, "input", "IDEoptionCheckbox");
    s.type = "checkbox";
    s.checked = true;
    r = s;
  }
  if (!u && e["project.buildType"] === "Standard EXE") {
    let e = createDOMElement(n, "div", "IDEoption");
    e.title =
      "视觉样式:\n\n当此设置为ON时，将嵌入到生成的可执行文件中的清单文件将导致Windows主题标准控件。\n\n强烈建议您将此选项保持为ON。";
    let t = createDOMElement(
      e,
      "div",
      "IDEoptionHeader ProjectoptionHeader",
      "视觉样式"
    );
    let o = createDOMElement(
      t,
      "div",
      "IDEoptionSubHeader",
      "(通过嵌入的清单文件)"
    );
    let i = createDOMElement(e, "div", "IDEoptionValue");
    let r = createDOMElement(i, "input", "IDEoptionCheckbox");
    r.type = "checkbox";
    r.checked = true;
    s = r;
  }
  if (
    e["project.buildType"] === "ActiveX DLL" ||
    e["project.buildType"] === "ActiveX Control"
  ) {
    let t = createDOMElement(n, "div", "IDEoption");
    t.title =
      "注册到HKEY_LOCAL_MACHINE:\n\nVB6旧版编译器生成的DLL将自注册到HKEY_LOCAL_MACHINE注册表hive。 这需要在现代操作系统上具有提升权限。\n\n要避免此问题，您可以注册到HKEY_CURRENT_USER注册表hive，它不需要提升权限。\n\n注意：如果您的ActiveX主机（例如VB6，或Access等）运行于提升的权限下，则必须将您的ActiveX类注册到HKEY_LOCAL_MACHINE，否则主机将无法看到它。";
    let o = createDOMElement(
      t,
      "div",
      "IDEoptionHeader ProjectoptionHeader",
      "注册到HKEY_LOCAL_MACHINE"
    );
    let i = createDOMElement(
      o,
      "div",
      "IDEoptionSubHeader",
      "(设置 OFF 将注册到HKEY_CURRENT_USER)"
    );
    let r = createDOMElement(t, "div", "IDEoptionValue");
    let s = createDOMElement(r, "input", "IDEoptionCheckbox");
    s.type = "checkbox";
    s.checked =
      e["project.dllRegisterLocalMachine"] !== undefined
        ? e["project.dllRegisterLocalMachine"]
        : true;
    l = s;
  }
  if (c) {
    let e = createDOMElement(n, "div", "IDEoption");
    e.title =
      "包含通用控件：\n\n当此选项为ON时，将引用WinNativeCommonCtls包。 这允许您使用诸如TreeView，UpDown，MonthView和DTPicker等控件。";
    let t = createDOMElement(
      e,
      "div",
      "IDEoptionHeader ProjectoptionHeader",
      "包含通用控件"
    );
    let o = createDOMElement(
      t,
      "div",
      "IDEoptionSubHeader",
      "(添加引用WinNativeCommonCtls)"
    );
    let i = createDOMElement(e, "div", "IDEoptionValue");
    let r = createDOMElement(i, "input", "IDEoptionCheckbox");
    r.type = "checkbox";
    r.checked = true;
    d = r;
  }
  if (e["project.buildType"] === "Standard EXE") {
    let e = createDOMElement(n, "div", "IDEoption");
    e.title =
      "高DPI感知：\n\n当此选项设置为无时，在高DPI屏幕上，您的应用程序将被操作系统缩放，除非您自己管理嵌入的清单文件。\n\n当此选项设置为系统DPI感知或按每个监视器DPI感知时，您的应用程序将被视为DPI感知，并且不会被操作系统缩放。\n\n注意：如果将DPI感知设置为ON，并且您直接使用Win32 API图形调用，则必须在您的位置计算中考虑高DPI系统。";
    let t = createDOMElement(
      e,
      "div",
      "IDEoptionHeader ProjectoptionHeader",
      "高DPI感知"
    );
    let o = createDOMElement(e, "div", "IDEoptionValue");
    let i = createDOMElement(o, "select", "IDEoptionDropdown");
    var p = createDOMElement(
      undefined,
      "option",
      "IDEoptionDropdownOption",
      "无"
    );
    p.value = "无";
    i.appendChild(p);
    var f = createDOMElement(
      undefined,
      "option",
      "IDEoptionDropdownOption",
      "系统DPI感知"
    );
    f.value = "系统DPI感知";
    i.appendChild(f);
    var g = createDOMElement(
      undefined,
      "option",
      "IDEoptionDropdownOption",
      "按每个监视器DPI感知"
    );
    g.value = "按每个监视器DPI感知";
    i.appendChild(g);
    i.value = "系统DPI感知";
    a = i;
  }
  showModalDialog(
    n,
    [
      {
        id: "OKBTN",
        caption: "继续",
        onclick: () => {
          hideModalDialog();
          var e = {
            "project.name": i?.value,
            "project.optionExplicit": r?.checked,
            "misc.visualStyles": s?.checked,
            "project.forceDpiAwarenessAtStartup": a?.value,
            "project.dllRegisterLocalMachine": l?.checked,
            "misc.winNativeCommonCtls": d?.checked,
          };
          o(e);
        },
        isDefaultAcceptAction: true,
      },
    ],
    "TwinBASIC新项目选项"
  );
  i.select();
  i.focus();
}
var ignoreAltKey = false;
var altKeyDown = false;
var shiftKeyDown = false;
var addinKeys = {};
function initKeyboardShortcuts() {
  document.onkeydown = globalKeyDown;
  setTimeout(() => {
    document.onkeyup = globalKeyUp;
  }, 1e3);
  document.addEventListener("mousedown", globalMouseDown, true);
  document.addEventListener("keypress", globalKeyPress, true);
  document.addEventListener("keydown", globalKeyDownCapture, true);
  document.oncopy = (e) => propagateFocusedEvent("oncopy", e);
  document.onpaste = (e) => propagateFocusedEvent("onpaste", e);
  document.oncut = (e) => propagateFocusedEvent("oncut", e);
}
function propagateFocusedEvent(e, t) {
  var o = document.activeElement;
  while (o) {
    if (o[e]) {
      o[e](t);
      break;
    }
    o = o.parentNode;
  }
}
function globalMouseDown(e) {
  altKeyDown = false;
}
function globalKeyPress(e) {
  if (e.key.charCodeAt(0) == 25) {
    propagateFocusedEvent("onredo", e);
  } else if (e.key.charCodeAt(0) == 26) {
    debugger;
    propagateFocusedEvent("onundo", e);
  }
}
function globalKeyDownCapture(e) {
  if (altKeyDown) {
    if (e.key != "Alt") {
      altKeyDown = false;
    }
  }
}
function toggleFullScreenMode() {
  if (codePanel.classList.contains("codePanelFullScreen")) {
    codePanel.classList.remove("codePanelFullScreen");
  } else {
    codePanel.classList.add("codePanelFullScreen");
  }
  changedSize();
}
function runOrPreviewClick() {
  if (!openEditors.selectedEditorNode) {
    debugOutputLine("runCodeUnderCursor failed: no active text editor.");
    return;
  }
  if (openEditors.selectedEditorNode.fileHandler === fileHandler_tbform) {
    openEditors.selectedEditorNode.domContainer.globalVars.menuBarPreview.onclick();
  } else {
    if (currentComponentFormDesignerId) {
      allowCompilerProcessToSetForegroundWIndow(() => {
        debugSocket.request("onClickedPreview", {
          uri: "",
          FormDesignerId: currentComponentFormDesignerId,
          serializedForm: null,
          docVersion: 0,
        });
      });
    } else {
      var e = editor.getPosition();
      debugSocket.request(
        "runCodeUnderCursor",
        {
          uri: openEditors.selectedEditorNode.fileNode.getFullPath(),
          line: e.lineNumber,
          character: e.column,
        },
        (e) => {
          if (!e.success) {
            debugOutputLine(e.message, "debugConsoleEvaluateResultText");
          }
        }
      );
    }
  }
}
function handleArrowDown() {
  var e = currentSubMenuDescriptor
    ? currentSubMenuDescriptor
    : currentMenuDescriptor;
  if (e) {
    var t = currentFocusedMenuItem === undefined ? true : false;
    e.every((e) => {
      if (t) {
        if (e.name && !e.isHidden && e.domObject) {
          setFocusedMenuItem(e);
          return false;
        }
      } else {
        if (e === currentFocusedMenuItem) {
          t = true;
        }
      }
      return true;
    });
  }
}
function registerAddInKeyboardShortcut(e, t) {
  e = e.toLowerCase();
  e = e.replace(/\s/g, "");
  let o = addinKeys[e];
  if (!o) {
    addinKeys[e] = [];
    o = addinKeys[e];
  }
  o.push(t);
}
function unregisterAddInKeyboardShortcuts() {
  addinKeys = {};
}
function globalKeyUp(e) {
  if (Object.keys(addinKeys).length > 0) {
    var t = "";
    if (e.ctrlKey) t += "{ctrl}";
    if (e.shiftKey) t += "{shift}";
    if (e.altKey) t += "{alt}";
    t += e.key.toLowerCase();
    let o = addinKeys[t];
    if (o) {
      o.forEach((e) => e());
    }
  }
  if (e.key == "Control" && e.repeat == false) {
    if (codeHintsVisibility == -1) {
      var o = document.querySelector(":root");
      o.style.setProperty("--inlineDecorationsDisplay", "none");
    }
  }
  if (e.key == "Alt" && altKeyDown) {
    altKeyDown = false;
    if (!ignoreAltKey && lockUICount == 0) showFileMenu();
  }
  if (e.key == "Shift") {
    shiftKeyDown = false;
  }
}
function simulateSpaceKey() {
  debugSocket.simulateSpaceKey();
}
function focusDebugConsoleEntry() {
  debugConsoleEntry.focus();
  debugConsoleEntry.select();
}
function globalKeyDown(e) {
  if (e.key == "Shift") {
    shiftKeyDown = true;
  }
  if (e.key == "Control" && e.repeat == false) {
    if (codeHintsVisibility == -1) {
      var t = document.querySelector(":root");
      t.style.setProperty("--inlineDecorationsDisplay", "inline-block");
    }
  }
  if (e.key == "Alt" && e.repeat == false) {
    altKeyDown = true;
  } else if (e.key == "Alt") {
  } else {
    altKeyDown = false;
  }
  if (e.key == "ArrowLeft") {
    if (currentSubMenuDescriptor) {
      hideContextMenuSub();
      if (preservedFocusedMainMenuItem)
        setFocusedMenuItem(preservedFocusedMainMenuItem);
      preservedFocusedMainMenuItem = undefined;
      return;
    }
    if (currentSelectedTopMenu) {
      currentSelectedTopMenu.navigatePrevMenu();
    }
  } else if (e.key == "ArrowRight") {
    if (currentSubMenuDescriptor) {
      return;
    }
    if (currentFocusedMenuItem && currentFocusedMenuItem.hoverAction) {
      preservedFocusedMainMenuItem = currentFocusedMenuItem;
      currentFocusedMenuItem.hoverAction(currentFocusedMenuItem.domObject);
      setTimeout(() => {
        if (currentSubMenuDescriptor) {
          handleArrowDown();
        }
      }, 100);
      return;
    }
    if (currentSelectedTopMenu) {
      currentSelectedTopMenu.navigateNextMenu();
    }
  } else if (e.key == "ArrowDown") {
    handleArrowDown();
  } else if (e.key == "ArrowUp") {
    var o = currentSubMenuDescriptor
      ? currentSubMenuDescriptor
      : currentMenuDescriptor;
    if (o) {
      var n = undefined;
      o.every((e) => {
        if (e === currentFocusedMenuItem) {
          if (n) {
            setFocusedMenuItem(n);
          }
          return false;
        }
        if (e.name && !e.isHidden && e.domObject) {
          n = e;
        }
        return true;
      });
    }
  } else if (e.key == "Enter") {
    if (currentFocusedMenuItem) {
      if (currentFocusedMenuItem.action(currentFocusedMenuItem)) return;
      hideContextMenu();
    }
  } else if (e.key == "Cancel") {
    pauseIcon.onclick();
  } else if (e.key == "s" && e.ctrlKey) {
    openEditors.save(openEditors.selectedEditorNode);
  } else if (e.key == "e" && e.ctrlKey) {
    exportProject();
  } else if (e.key == "M" && e.altKey && e.ctrlKey && e.shiftKey) {
    saveProjectMetaState(() => {});
    msgBox("保存项目元数据到文件。");
  } else if (e.key == "F1") {
    if (debugConsoleEntryIntellisenseBoxSignature.style.display !== "none") {
      toggleSigHelp();
    } else {
    }
    e.preventDefault();
    e.stopPropagation();
  } else if (e.key == "F5") {
    debugSocket.continue();
    e.preventDefault();
  } else if (e.key == "F6") {
    runOrPreviewClick();
  } else if (e.key == "F8") {
    if (liveIDEOptions.f8keyMode === "debug") {
      if (e.shiftKey) {
        if (e.ctrlKey) {
          debugStepOutIcon.onclick();
        } else {
          debugStepOverIcon.onclick();
        }
      } else {
        debugStepIntoIcon.onclick();
      }
      e.stopPropagation();
    }
  } else if (e.key == "F9") {
    if (e.ctrlKey) {
      setCurrentThreadExecutionPoint();
    } else {
      toggleBreakpointAtLine();
    }
  } else if (e.key == "F10") {
    debugSocket.stepOver();
  } else if (e.key == "F11") {
    if (e.shiftKey) {
      debugSocket.stepOut();
    } else {
      debugSocket.stepInto();
    }
  } else if (e.key == "F4") {
    if (!e.altKey && !e.ctrlKey) {
      toggleFullScreenMode();
    } else if (!e.altKey && e.ctrlKey) {
      openEditors.closeFile(openEditors.selectedEditorNode);
    }
  } else if (e.key == "W" || e.key == "w") {
    if (!e.altKey && e.ctrlKey) {
      openEditors.closeFile(openEditors.selectedEditorNode);
    }
  } else if (e.key == "F" || e.key == "f") {
    if (e.ctrlKey) {
      if (e.shiftKey) {
        searchIcon.click();
      }
    }
  } else if (e.key == "Tab" && e.ctrlKey) {
    if (!e.shiftKey) {
      if (
        openEditors.selectedEditorNode.tabElement.nextSibling &&
        openEditors.selectedEditorNode.tabElement.nextSibling.editorNode
      ) {
        openEditors.changeSelectedEditor(
          openEditors.selectedEditorNode.tabElement.nextSibling.editorNode
        );
      } else {
        openEditors.changeSelectedEditor(
          openEditors.selectedEditorNode.tabElement.parentNode.children[0]
            .editorNode
        );
      }
    } else {
      if (
        openEditors.selectedEditorNode.tabElement.previousSibling &&
        openEditors.selectedEditorNode.tabElement.previousSibling.editorNode
      ) {
        openEditors.changeSelectedEditor(
          openEditors.selectedEditorNode.tabElement.previousSibling.editorNode
        );
      } else {
        openEditors.changeSelectedEditor(
          openEditors.selectedEditorNode.tabElement.parentNode.children[
            openEditors.selectedEditorNode.tabElement.parentNode.children
              .length - 1
          ].editorNode
        );
      }
    }
  } else if (e.key == "+" && e.ctrlKey) {
    if (e.altKey) {
      liveIDEOptions["fontSize"] =
        parseInt(liveIDEOptions["fontSize"]) + 1 + "px";
      liveIDEOptions["codeFontSize"] =
        parseInt(liveIDEOptions["codeFontSize"]) + 1 + "px";
    } else {
      liveIDEOptions["codeFontSize"] =
        parseInt(liveIDEOptions["codeFontSize"]) + 1 + "px";
    }
    changedIdeOptions();
    saveIDEOptions();
  } else if (e.key == "-" && e.ctrlKey) {
    if (e.altKey) {
      let e = parseInt(liveIDEOptions["fontSize"]);
      if (e > 8) {
        liveIDEOptions["fontSize"] = e - 1 + "px";
      }
      e = parseInt(liveIDEOptions["codeFontSize"]);
      if (e > 8) {
        liveIDEOptions["codeFontSize"] = e - 1 + "px";
      }
      changedIdeOptions();
      saveIDEOptions();
    } else {
      let e = parseInt(liveIDEOptions["codeFontSize"]);
      if (e > 8) {
        liveIDEOptions["codeFontSize"] = e - 1 + "px";
        changedIdeOptions();
        saveIDEOptions();
      }
    }
  } else if ((e.key == "g" || e.key == "G") && e.ctrlKey) {
    focusDebugConsoleEntry();
  } else if (e.key == "1" && e.ctrlKey) {
    codePanelDropDownComponent.focus();
    codePanelDropDownComponent.onmousedown({ detail: 1 });
    simulateSpaceKey();
  } else if (e.key == "2" && e.ctrlKey) {
    codePanelDropDownScope.focus();
    codePanelDropDownScope.onmousedown({ detail: 1 });
    simulateSpaceKey();
  } else if (e.key == "3" && e.ctrlKey) {
    codePanelDropDownProcedure.focus();
    codePanelDropDownProcedure.onmousedown({ detail: 1 });
    simulateSpaceKey();
  }
}
var lspSocket;
const MessageLSPRequest = 0;
var statusErrorsDiv = undefined;
var errorCountDiv = undefined;
var statusWarningsDiv = undefined;
var warningCOuntDiv = undefined;
var kofiIconDiv = undefined;
var discordIconDiv = undefined;
var twitterIconDiv = undefined;
var githubIconDiv = undefined;
var globalUndoStackGroupId = 0;
function uniqueControls(e) {
  var t = {};
  return e.filter((e) =>
    t.hasOwnProperty(e.clsid) ? false : (t[e.clsid] = true)
  );
}
function updateFolderErrorCounts(e, t, o) {
  var n = e.parentFolder;
  while (n) {
    n.cachedDiagnostics_childErrorCount += t;
    n.cachedDiagnostics_childWarningCount += o;
    if (n.innerDiv) {
      if (n.cachedDiagnostics_childErrorCount) {
        n.innerDiv.classList.remove("warning");
        n.innerDiv.classList.add("error");
      } else if (n.cachedDiagnostics_childWarningCount) {
        n.innerDiv.classList.remove("error");
        n.innerDiv.classList.add("warning");
      } else {
        n.innerDiv.classList.remove("error");
        n.innerDiv.classList.remove("warning");
      }
    }
    n = n.parentFolder;
  }
  errorCountDiv.innerText =
    fs.tree.rootFolder.cachedDiagnostics_childErrorCount;
  warningCountDiv.innerText =
    fs.tree.rootFolder.cachedDiagnostics_childWarningCount;
}
class _LSPSocket {
  constructor() {
    this.requestsAwaitingResponse = {};
    this.sequenceId = 0;
    this.latestCustomControls = [];
  }
  connect(e, t) {
    this.callback = t;
    this.webSocket = new webSocketJson(
      "ws://localhost:" + e + "/" + compilerPassKey + "/language",
      this
    );
    connectionStateChanged();
  }
  onConnected() {
    this.callback();
  }
  event_window_showMessage(e) {
    msgBox(e.params.message);
  }
  event_window_showMessage2(e) {
    showModalNotification(e.params.message);
  }
  event_textDocument_publishDiagnostics(e) {
    {
      var t = e.params.uri;
      var o = fs.tree.resolvePath(t);
      if (o) {
        if (
          e.params.docVersion === 0 ||
          o.ideVersionId === 0 ||
          e.params.docVersion === o.ideVersionId
        ) {
          var n = e.params.errorCount - o.cachedDiagnostics_errorCount;
          var i = e.params.warningCount - o.cachedDiagnostics_warningCount;
          o.cachedDiagnostics = e.params.diagnostics;
          o.cachedDiagnostics_errorCount = e.params.errorCount;
          o.cachedDiagnostics_warningCount = e.params.warningCount;
          if (n || i) {
            updateFolderErrorCounts(o, n, i);
          }
          syncFileDiagnosticsToEditor(o);
          syncFileDiagnosticsToExplorer(o);
          problemsPanel.syncFileProblems(o);
        } else {
        }
      }
    }
  }
  request_custom_applyEdit(e) {
    {
      e.params.edit.documentChanges.forEach((t) => {
        var o = t.textDocument.uri;
        var n = t.textDocument.version;
        var i = fs.tree.resolvePath(o);
        var r = i.ideVersionId;
        if (i && i.openEditorNode) {
          var s = undefined;
          if (i.openEditorNode === openEditors.selectedEditorNode) {
            s = editor.getPosition();
          }
          var a = [];
          var l = false;
          t.edits.forEach((e) => {
            if (e.isEndBlock) {
              e.newText = "\t" + e.newText;
              if (s) s.column += 1;
            }
            if (!e.isEndBlock && s && s.lineNumber === e.range.start.line + 1) {
              e.docVersion = n;
              i.openEditorNode.pendingLineEdits.push(e);
            } else {
              if (n === r) {
                var t = {
                  range: new monaco.Range(
                    e.range.start.line + 1,
                    e.range.start.character + 1,
                    e.range.end.line + 1,
                    e.range.end.character + 1
                  ),
                  text: e.newText,
                  forceMoveMarkers: true,
                };
                a.push(t);
                if (!e.noUndo) {
                  l = true;
                }
              } else {
                if (e.wasEnterKeyTriggeredCount) {
                  if (e.wasEnterKeyTriggeredCount < 5) {
                    lspSocket.request(
                      "textDocument/enterKeyRetrigger",
                      {
                        textDocument: { uri: o, version: i.ideVersionId },
                        enterKeyAtLine: e.range.start.line,
                        retriggerCount: e.wasEnterKeyTriggeredCount,
                      },
                      (e) => {}
                    );
                  }
                }
              }
            }
          });
          if (a.length > 0) {
            if (l) {
              i.openEditorNode.monacoModelInstance.pushEditOperations([], a);
            } else {
              var d =
                i.openEditorNode.monacoModelInstance._undoRedoService._editStacks.get(
                  i.openEditorNode.monacoModelInstance.uri._formatted
                );
              var c = d._past.length;
              var u = c - 1;
              i.openEditorNode.monacoModelInstance.pushEditOperations([], a);
              if (u >= 0) {
                var p = d._past[u].groupId;
                if (p === 0) {
                  globalUndoStackGroupId++;
                  p = globalUndoStackGroupId;
                }
                while (u < d._past.length) {
                  d._past[u].groupId = p;
                  u++;
                }
              }
            }
            if (s && e.params.PreserveCaretPosition) {
              editor.setPosition(s);
            }
          }
        } else {
          debugOutputLine(
            "received request_custom_applyEdit for file that isn't being edited: " +
              o,
            "debugConsoleErrorText"
          );
        }
      });
    }
  }
  request_custom_buildUnregisterFailed() {
    var e = createDOMElement(
      undefined,
      "div",
      "simpleMsgBox",
      "Build failed: unable to unregister the previous DLL.   Continue anyway?"
    );
    showModalDialog(e, [
      {
        caption: "Delete It And Continue",
        onclick: () => {
          hideModalDialog();
          debugSocket.build(false, true);
        },
      },
      {
        caption: "取消",
        onclick: hideModalDialog,
        isDefaultCancelAction: true,
      },
    ]);
  }
  request_custom_provideTests() {}
  IconProcessingIncCount() {
    this.iconProcessingCount++;
  }
  IconProcessingDecCount() {
    this.iconProcessingCount--;
    if (this.iconProcessingCount == 0) {
      openEditors.tree.rootFolder.enumerateContent(false, (e) => {
        if (e.fileHandler === fileHandler_tbform) {
          if (e.domContainer) {
            formDesigner_updateControlsList(
              e.domContainer.globalVars,
              this.latestCustomControls
            );
          }
        }
        return true;
      });
    }
  }
  request_custom_provideCustomControls(e) {
    if (this.latestCustomControls !== undefined) {
    }
    this.latestCustomControls = uniqueControls(e.params.customControls);
    this.iconProcessingCount = 0;
    this.IconProcessingIncCount();
    this.latestCustomControls.forEach((e) => {
      if (e.iconData) {
        var t = "data:image;base64," + e.iconData;
        this.IconProcessingIncCount();
        getTransparentPngFromBitmapWithKeyColor(t, (t) => {
          e.iconData = t.replace("data:image/png;base64,", "");
          this.IconProcessingDecCount();
        });
      }
    });
    this.IconProcessingDecCount();
  }
  request_custom_provideFormDesignerEventsUpdate(e) {
    formDesignerEventsUpdate(e.params);
  }
  onReceivedObject(e) {
    if (e.method) {
      if (e.id) {
        var t = "request_" + e.method.replace("/", "_");
        var o = this[t];
        if (o) {
          o.call(this, e);
          return;
        } else {
          alert("LSP请求: " + e.method.toString());
        }
      } else {
        var t = "event_" + e.method.replace("/", "_");
        var o = this[t];
        if (o) {
          o.call(this, e);
          return;
        } else {
          alert("LSP事件: " + e.method.toString());
        }
      }
    } else {
      var n = e.id;
      var i = this.requestsAwaitingResponse[n];
      if (i) {
        delete this.requestsAwaitingResponse[n];
        i(e);
      }
    }
  }
  request(e, t, o) {
    this.requestsAwaitingResponse[this.sequenceId] = o;
    this.webSocket.sendObject({ id: this.sequenceId++, method: e, params: t });
  }
  event(e, t) {
    this.webSocket.sendObject({ method: e, params: t });
  }
}
function initLspSocket() {
  statusErrorsDiv = document.getElementById("statusErrors");
  errorCountDiv = document.getElementById("errorCount");
  statusWarningsDiv = document.getElementById("statusWarnings");
  warningCountDiv = document.getElementById("warningCount");
  kofiIconDiv = document.getElementById("kofiIcon");
  discordIconDiv = document.getElementById("discordIcon");
  twitterIconDiv = document.getElementById("twitterIcon");
  githubIconDiv = document.getElementById("githubIcon");
  lspSocket = new _LSPSocket();
  connectionStateChanged();
  kofiIconDiv.onclick = () => {
    root.Shell('cmd.exe /c start "link" "https://ko-fi.com/twinbasic"');
  };
  discordIconDiv.onclick = () => {
    root.Shell('cmd.exe /c start "link" "https://discord.gg/UaW9GgKKuE"');
  };
  twitterIconDiv.onclick = () => {
    root.Shell('cmd.exe /c start "link" "https://twitter.com/waynephillipsea"');
  };
  githubIconDiv.onclick = () => {
    root.Shell(
      'cmd.exe /c start "link" "https://github.com/twinbasic/twinbasic"'
    );
  };
}
var layoutChangesPending = 1;
var hiddenDiv;
Array.prototype.peek = function () {
  if (this.length === 0) {
    throw new Error("out of bounds");
  }
  return this[this.length - 1];
};
function initMisc() {
  hiddenDiv = createDOMElement(undefined, "div");
}
function createDOMElement(e, t, o, n) {
  var i = document.createElement(t);
  if (o) i.classList = o;
  if (n) i.innerText = n;
  if (t === "input") i.spellcheck = false;
  if (e) e.appendChild(i);
  return i;
}
function freezeLayoutChanges() {
  layoutChangesPending++;
  if (layoutChangesPending == 1) {
    document.getElementById("bodyInner").classList.add("displayNone");
  }
}
function unfreezeLayoutChanges() {
  layoutChangesPending--;
  if (layoutChangesPending == 0) {
    document.getElementById("bodyInner").classList.remove("displayNone");
  }
}
function doLayoutChanges(e) {
  freezeLayoutChanges();
  try {
    e();
  } catch (e) {}
  unfreezeLayoutChanges();
}
function copyToClipboard(e) {
  alert(e.toString());
}
function bufferToBase64Async(e, t) {
  var o = new Blob([e], { type: "application/octet-binary" });
  var n = new FileReader();
  n.onload = function () {
    var e = n.result;
    var o = e.substr(e.indexOf(",") + 1);
    t(o);
  };
  n.readAsDataURL(o);
}
function base64ToBufferAsync(e, t) {
  var o = "data:application/octet-binary;base64," + e;
  fetch(o)
    .then((e) => e.arrayBuffer())
    .then((e) => {
      t(e);
    });
}
function readBinaryFile(e, t) {
  var o = new XMLHttpRequest();
  o.responseType = "arraybuffer";
  o.open("GET", e, true);
  o.onreadystatechange = function () {
    if (o.readyState === 4) {
      if (o.status === 200 || o.status == 0) {
        debugger;
        var e = o.response;
        t(e);
      }
    }
  };
  o.send(null);
}
function displayVirtualFile(e) {
  var t;
  var o = {
    name: e.displayName,
    fileNode: { toolTip: e.tooltip },
    fileHandler: {
      activated(o, n, i, r) {
        o.type = "VirtualPreview";
        statusLineCol.classList.add("hide");
        codePanelMainInnerMonacoContainer.classList.add("hide");
        codePanelDropDownContainer.classList.add("hideNotCodeEditor");
        changedSize();
        o.domObject_CloseButton.className = "tabItemIconRight";
        if (!t) {
          t = createDOMElement(
            codePanelMainInner,
            "div",
            "virtualDocumentContainer"
          );
          t.innerHTML = e.html;
          if (e.onCreateDom) e.onCreateDom(t);
        } else {
          t.classList.remove("hide");
        }
        outlinePanel.syncSymbols([]);
      },
      onFocus(e) {
        t.focus();
      },
      onReveal(e, t, o, n) {},
      isDirty(e) {
        return false;
      },
      deactivated(e) {
        t.classList.add("hide");
      },
      save(e) {},
      closing(e, t, o) {
        o();
      },
      closed(e) {
        codePanelMainInner.removeChild(t);
        t = undefined;
      },
    },
    tree: openEditors.tree,
  };
  o.tabElement = openEditors.createTabElement(o, false);
  openEditors.changeSelectedEditor(o, false, false, false);
  changedSize();
}
function displayVirtualFileInMonaco(e) {
  var t;
  var o = {
    name: e.displayName,
    fileNode: { toolTip: e.tooltip },
    fileHandler: {
      activated(t, o, n, i) {
        t.type = "VirtualMonaco";
        clearEditor();
        editor.updateOptions({ glyphMargin: false, readOnly: true });
        if (!t.monacoModelInstance) {
          t.monacoModelInstance = monaco.editor.createModel("", "twinbasic");
          if (liveIDEOptions["tabSize"])
            t.monacoModelInstance.updateOptions({
              tabSize: liveIDEOptions["tabSize"],
            });
        }
        editor.setModel(t.monacoModelInstance);
        monaco.editor.setModelLanguage(t.monacoModelInstance, e.lang);
        lineNum.innerText = 1;
        columnNum.innerText = 1;
        if (t.monacoViewState) {
          editor.restoreViewState(t.monacoViewState);
        }
        statusLineCol.classList.remove("hide");
        codePanelMainInnerMonacoContainer.classList.remove("hide");
        codePanelDropDownContainer.classList.add("hideNotCodeEditor");
        changedSize();
        if (!o) editor.focus();
        t.monacoModelInstance.setValue(e.text);
        t.domObject_CloseButton.className = "tabItemIconRight";
      },
      deactivated(e) {
        e.monacoViewState = editor.saveViewState();
      },
      undo(e) {},
      redo(e) {},
      isDirty(e) {
        return false;
      },
      save(e, t) {
        if (t) t();
      },
      resyncToFileSystem(e) {},
      closing(e, t, o) {
        if (o) o();
      },
      closed(e) {},
      onFocus(e) {
        editor.focus();
      },
      gotFileData(e, t) {
        debugger;
      },
    },
    tree: openEditors.tree,
  };
  o.tabElement = openEditors.createTabElement(o, false);
  openEditors.changeSelectedEditor(o, false, false, false);
  changedSize();
}
function generateUUID() {
  return "{" + generateUUID2() + "}";
}
function generateUUID2() {
  var e = new Date().getTime();
  var t = (performance && performance.now && performance.now() * 1e3) || 0;
  return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (o) {
    var n = Math.random() * 16;
    if (e > 0) {
      n = (e + n) % 16 | 0;
      e = Math.floor(e / 16);
    } else {
      n = (t + n) % 16 | 0;
      t = Math.floor(t / 16);
    }
    return (o === "x" ? n : (n & 3) | 8).toString(16).toUpperCase();
  });
}
function sortObjectByKeys(e, t) {
  return Object.keys(e)
    .sort(t)
    .reduce((t, o) => ((t[o] = e[o]), t), {});
}
function JSONstringifyOrdered(e, t) {
  var o = [];
  var n = {};
  JSON.stringify(e, function (e, t) {
    if (!(e in n)) {
      o.push(e);
      n[e] = null;
    }
    return t;
  });
  o.sort();
  return JSON.stringify(e, o, t);
}
function parseNumeric(e, t) {
  var o = parseInt(e);
  if (isNaN(o)) o = t;
  if (o === undefined) o = 0;
  return o;
}
function parseJson(e, t) {
  try {
    return JSON.parse(e);
  } catch (e) {
    return t;
  }
}
function JSONfn_stringify(e) {
  return JSON.stringify(e, (e, t) =>
    typeof t === "function" ? "~" + t.toString() : t
  );
}
function JSONfn_parse(str) {
  return JSON.parse(str, (key, value) => {
    if (typeof value !== "string") return value;
    return value.substring(0, 1) === "~"
      ? eval(eval(`function ${value.substring(1)}; ${key}`))
      : value;
  });
}
function serverHttpsGetUtf8(e, t, o) {
  const n = new XMLHttpRequest();
  n.open("GET", "https://www.everythingaccess.com" + e);
  n.overrideMimeType("text/plain; charset=utf-8");
  n.send();
  n.onreadystatechange = (e) => {
    if (n.readyState === 4) {
      if (n.status === 200) {
        t(n.responseText);
      } else {
        o();
      }
    }
  };
}
function serverHttpsGetBinary(e, t, o) {
  const n = new XMLHttpRequest();
  n.open("GET", "https://www.everythingaccess.com" + e);
  n.responseType = "arraybuffer";
  n.send();
  n.onreadystatechange = (e) => {
    if (n.readyState === 4) {
      if (n.status === 200) {
        t(n.response);
      } else {
        o();
      }
    }
  };
}
function TEXTtoHTML(e) {
  e = e.replace(/&/g, "&amp;");
  e = e.replace(/</g, "&lt;");
  e = e.replace(/>/g, "&gt;");
  e = e.replace(/\\/g, "&#92;");
  return e;
}
function intToUint8Array(e) {
  return Uint8Array.of(
    (e & 255) >> 0,
    (e & 65280) >> 8,
    (e & 16711680) >> 16,
    (e & 4278190080) >> 24
  );
}
function syncWait(e) {
  var t = Date.now();
  while (Date.now() - t < e) {}
}
function createWebsocketWithFallback(e) {
  return new WebSocket(e);
}
function deepclone(e) {
  if (e === null || "clonePreventRecursion" in e) return e;
  var t = {};
  for (var o in e) {
    e["clonePreventRecursion"] = null;
    let n = e[o];
    t[o] = typeof n === "object" ? deepclone(n) : n;
    delete e["clonePreventRecursion"];
  }
  return t;
}
function shallowclone(e) {
  var t = {};
  for (var o in e) {
    let n = e[o];
    t[o] = typeof n === "object" ? null : n;
  }
  return t;
}
function copyEvent(e) {
  let t = shallowclone(e);
  if (e.target) t.target = { id: e.target.id, value: e.target.value };
  return t;
}
function raiseEvent(e, t, o, ...n) {
  var i = t.target.parentNode;
  while (!i.rootEventHandler) i = i.parentNode;
  var r = 0;
  while (r < n.length) {
    t["customData" + r] = n[r];
    r += 1;
  }
  if (i.rootEventHandler) {
    i.rootEventHandler[e](t);
  }
  if (o) t.stopPropagation();
}
var baseURL = undefined;
var editor = undefined;
var decorations = [];
var hoverBreakpoints = [];
var lineSplitterDecorations = [];
var psuedoCompletionProvider = undefined;
var realCompletionProvider = undefined;
var creatingRealCompletionProvider = false;
var currentCompletionProviderRequest = 0;
var realCompletionProviderHasExactMatch = false;
var codePanelMainInner = undefined;
var errorWidgetViewZoneId = undefined;
var codePanelMainInnerMonacoContainer = undefined;
var statusLineCol = undefined;
var monacoTopPosition = undefined;
var codePanel = undefined;
var glyphMouseDownTimeStart = undefined;
var glyphMouseDownTimer = undefined;
var glyphMouseDragging = false;
var nextTriggerIsFromCtrlSpace = false;
var revealedLine = undefined;
var revealedLineTime = 0;
var revealedLineViewPortTop = false;
var revealedLineColumn = undefined;
var cachedFoldingRanges = undefined;
const suggestionFixUp = [
  0, 1, 2, 1, 2, 3, 4, 5, 7, 8, 9, 11, 12, 15, 13, 15, 16, 17, 18, 21, 16, 14,
  6, 10,
];
var expectedClipboardTextLineIndent = 0;
var expectedClipboardText = "";
var isClickOnSigHelpToggle = false;
var sigHelpIsExpanded = false;
var currentSigHelpExpandedHtml;
var currentSigHelpCollapsedHtml;
var TemporaryDisabledKeys = {};
var SpecialKeysThatCloseIntellisense = {
  PrintScreen: true,
  Escape: true,
  ArrowLeft: true,
  ArrowRight: true,
  ArrowUp: true,
  ArrowDown: true,
  Tab: true,
};
var SpecialKeysThatAcceptSelectedIntellisense = {
  ",": true,
  ".": true,
  "+": true,
  "-": true,
  "&": true,
  "(": true,
  ")": true,
  "!": true,
  "*": true,
  "/": true,
  "\\": true,
  ":": true,
  "=": true,
};
var KeysThatDontTriggerIntellisense = {
  "@": true,
  "?": true,
  "/": true,
  "\\": true,
  "<": true,
  ">": true,
  ";": true,
  ":": true,
  "[": true,
  "]": true,
  "{": true,
  "}": true,
  "+": true,
  "-": true,
  "*": true,
  "&": true,
  "^": true,
  "%": true,
  $: true,
  '"': true,
  "`": true,
  "'": true,
};
var LegacyKeysThatTriggerIntellisense = {
  "(": true,
  ".": true,
  ",": true,
  "=": true,
  " ": true,
};
var memUsageDiv;
var userObjectsDiv;
var gdiObjectsDiv;
var statusMemUsageDiv;
function setNativeValue(e, t) {
  const { set: o } = Object.getOwnPropertyDescriptor(e, "value") || {};
  const n = Object.getPrototypeOf(e);
  const { set: i } = Object.getOwnPropertyDescriptor(n, "value") || {};
  if (i && o !== i) {
    i.call(e, t);
  } else if (o) {
    o.call(e, t);
  } else {
    throw new Error("The given element does not have a value setter");
  }
}
function changedSize() {
  leftPanel.style.maxHeight = 0;
  rightPanel.style.maxHeight = 0;
  codePanelMainInner.style.height = "0px";
  codePanelMainInner.style.width = "0px";
  leftPanel.style.maxHeight =
    document.body.offsetHeight -
    rootMenu1.offsetHeight -
    rootStatusBar.offsetHeight +
    "px";
  rightPanel.style.maxHeight =
    document.body.offsetHeight -
    rootMenu1.offsetHeight -
    rootStatusBar.offsetHeight +
    "px";
  editor.layout({
    width: codePanelMain.clientWidth,
    height: codePanelMain.clientHeight,
  });
  codePanelMainInner.style.width = codePanelMain.clientWidth + "px";
  codePanelMainInner.style.height = codePanelMain.clientHeight + "px";
  syncTitleBar();
  if (modalDialogContainer.style.display === "block") RepositionModalDialog();
}
var allCurrentWidgets = [];
function clearAllWidgets() {
  allCurrentWidgets.forEach((e) => {
    editor.removeOverlayWidget(e);
    editor.changeViewZones(function (t) {
      t.removeZone(e.zoneId);
    });
  });
  allCurrentWidgets = [];
}
var widgetUniqueId = 0;
function addCodeLens(e, t, o, n, i) {
  let r = createDOMElement(undefined, "div", "codeLensWidget");
  let s = createDOMElement(r, "div", "codeLensWidgetIndent");
  let a = createDOMElement(r, "div", "codeLensWidgetText");
  s.innerText = new Array(t).join(" ");
  a.innerHTML = o;
  r.id = "overlayId1";
  a.onclick = () => {
    executeCommand(n, i);
  };
  let l = widgetUniqueId++;
  let d = {
    getId: () => "overlay.zone.widget" + l,
    getDomNode: () => r,
    getPosition: () => null,
  };
  allCurrentWidgets.push(d);
  editor.addOverlayWidget(d);
  let c = document.createElement("div");
  c.id = "zoneId";
  editor.changeViewZones(function (t) {
    d.zoneId = t.addZone({
      afterLineNumber: e - 1,
      get heightInPx() {
        const e = editor.getLayoutInfo();
        r.style.width =
          e.width - e.verticalScrollbarWidth - e.contentLeft + "px";
        r.style.left = e.contentLeft + "px";
        return r.offsetHeight;
      },
      domNode: c,
      onDomNodeTop: (e) => {
        r.style.top = e + "px";
        const t = editor.getLayoutInfo();
        r.style.width =
          t.width - t.verticalScrollbarWidth - t.contentLeft + "px";
        r.style.left = t.contentLeft + "px";
      },
      onComputedHeight: (e) => {
        r.style.height = e + "px";
        const t = editor.getLayoutInfo();
        r.style.width =
          t.width - t.verticalScrollbarWidth - t.contentLeft + "px";
        r.style.left = t.contentLeft + "px";
      },
    });
  });
}
function hideErrorWidget() {
  if (lastOverlayWidget) {
    editor.removeOverlayWidget(lastOverlayWidget);
    lastOverlayWidget = undefined;
  }
  if (errorWidgetViewZoneId) {
    editor.changeViewZones(function (e) {
      e.removeZone(errorWidgetViewZoneId);
      errorWidgetViewZoneId = undefined;
    });
  }
}
var lastOverlayWidget;
function showErrorWidget(t) {
  hideErrorWidget();
  let o = createDOMElement(undefined, "div", "errorWidget");
  let n = createDOMElement(o, "div", "errorWidgetHeader");
  let i = createDOMElement(n, "div", "errorWidgetHeaderText");
  let r = createDOMElement(n, "div", "errorWidgetHeaderClose");
  let s = createDOMElement(o, "div", "errorWidgetText");
  i.innerText = activeDebuggingErrorHeader
    ? activeDebuggingErrorHeader
    : "ERROR OCCURRED";
  let a = createDOMElement(s, "div", "errorWidgetTextLeft");
  a.innerText = "   DESCRIPTION:";
  let l = createDOMElement(s, "div", "errorWidgetTextRight");
  l.innerText = activeDebuggingError;
  if (activeDebuggingSource) {
    let e = createDOMElement(o, "div", "errorWidgetText");
    let t = createDOMElement(e, "div", "errorWidgetTextLeft");
    t.innerText = "   SOURCE:";
    let n = createDOMElement(e, "div", "errorWidgetTextRight");
    n.innerText = activeDebuggingSource;
  }
  o.id = "overlayId";
  o.onclick = () => {};
  r.onclick = () => {
    hideErrorWidget();
    e.stopPropagation();
  };
  let d = {
    getId: () => "overlay.zone.widget",
    getDomNode: () => o,
    getPosition: () => null,
  };
  lastOverlayWidget = d;
  editor.addOverlayWidget(d);
  let c = document.createElement("div");
  c.id = "zoneId";
  editor.changeViewZones(function (e) {
    errorWidgetViewZoneId = e.addZone({
      afterLineNumber: t,
      get heightInPx() {
        const e = editor.getLayoutInfo();
        o.style.width = e.width - e.verticalScrollbarWidth + "px";
        return o.offsetHeight;
      },
      domNode: c,
      onDomNodeTop: (e) => {
        o.style.top = e + "px";
        const t = editor.getLayoutInfo();
        o.style.width = t.width - t.verticalScrollbarWidth + "px";
      },
      onComputedHeight: (e) => {
        o.style.height = e + "px";
        const t = editor.getLayoutInfo();
        o.style.width = t.width - t.verticalScrollbarWidth + "px";
      },
    });
  });
}
function findClosestOutlinePanelItem(e, t, o) {
  var n = undefined;
  var i = 0;
  while (i < e.length) {
    var r = e[i++];
    if (
      r.kind &&
      (r.kind == 2 || r.kind == 5 || r.kind == 7 || r.kind == 9 || r.kind == 12)
    ) {
      if (r.range.start.line < t) {
        n = r;
      } else {
        if (o) {
          n = r;
        }
        break;
      }
    }
  }
  if (n) {
    if (n.children) {
      var s = findClosestOutlinePanelItem(n.children, t, o);
      if (s) n = s;
    }
  }
  return n;
}
function clearCurrentDocumentBreakpoints() {
  while (currentBreakpointDecorations.length) {
    var e = currentBreakpointDecorations.splice(0, 1);
    editor.deltaDecorations(e, []);
  }
}
function revealLineInEditor(e, t, o) {
  if (t == 0) {
    try {
      var n = editor.getModel().getLineContent(e);
      t = n.search(/\S|$/) + 1;
    } catch (e) {
      t = 1;
    }
  }
  if (t === undefined) t = 1;
  var i = new monaco.Position(parseInt(e), parseInt(t));
  editor.setPosition(i);
  if (o) {
    editor.revealLineNearTop(parseInt(e));
  } else {
    editor.revealLineInCenterIfOutsideViewport(parseInt(e));
  }
  revealedLine = parseInt(e);
  revealedLineColumn = parseInt(t);
  revealedLineViewPortTop = o;
  revealedLineTime = performance.now();
}
function setCurrentThreadExecutionPoint(e) {
  if (codePanelMainInnerMonacoContainer.classList.contains("hide")) return;
  if (e === undefined) {
    e = editor.getPosition().lineNumber;
  }
  debugSocket.changeDebugExecutionLine(e);
}
function toggleBreakpointAtLine(e) {
  if (codePanelMainInnerMonacoContainer.classList.contains("hide")) return;
  if (e === undefined) {
    e = editor.getPosition().lineNumber;
  }
  var t = editor.getModel();
  var o = undefined;
  var n = 0;
  currentBreakpointDecorations.forEach((i) => {
    if (t.getDecorationRange(i).startLineNumber === e) {
      o = n;
    }
    n++;
  });
  if (o !== undefined) {
    var i = currentBreakpointDecorations.splice(o, 1);
    editor.deltaDecorations(i, []);
  } else {
    currentBreakpointDecorations.push(
      editor.deltaDecorations(
        [],
        [
          {
            range: new monaco.Range(e, 1, e, 1),
            options: {
              isWholeLine: true,
              glyphMarginClassName: "marginGlyph breakpointActiveGlyph",
            },
          },
        ]
      )
    );
  }
  var r = { versionId: editor.getModel().getVersionId() };
  t.ourChangeContentHandler(r, true, true);
}
function clearDecorations() {
  decorations = editor.deltaDecorations(decorations, []);
}
function startGlyphDrag() {
  glyphMouseDownTimer = undefined;
  glyphMouseDragging = true;
  document.documentElement.style.setProperty(
    "--activeLineGlyphCursor",
    "grabbing"
  );
  document.documentElement.style.setProperty(
    "--activeLineGlyphTransform",
    "scale(0.8)"
  );
}
function cutOrCopy(e, t) {
  e.focus();
  const o = e.getSelection();
  if (!o || o.isEmpty()) {
    return;
  }
  var n = parseInt(liveIDEOptions["tabSize"]);
  var i = " ".repeat(n);
  debugOutputLineCopyPaste("tabSpacesCount: " + n);
  debugOutputLineCopyPaste("tabSpacesString: '" + i + "'");
  let r = e.getModel();
  var s = r?.getValueInRange(o);
  s = s.replaceAll("\t", i);
  debugSocket.request(
    "copyClipboardIDE",
    { text: s, extraData: o.startColumn - 1 },
    (e) => {}
  );
  if (t) {
    e.executeEdits("clipboard", [
      { range: o, text: "", forceMoveMarkers: true },
    ]);
  }
}
function cancelGlyphDrag() {
  glyphMouseDragging = false;
  hoverBreakpoints = editor.deltaDecorations(hoverBreakpoints, []);
  document.documentElement.style.setProperty("--activeLineGlyphCursor", "grab");
  document.documentElement.style.setProperty("--activeLineGlyphTransform", "");
}
function handleSelectedDebugConsoleIntellisenseEntryMonaco(e, t, o) {
  var n = debugConsoleEntryIntellisenseList.dataNodesDATA[e];
  debugConsoleEntryIntellisenseBox.style.display = "none";
  if (n.t == CompletionKindInfo) return false;
  var i = n.l;
  var r = debugConsoleEntryIntellisenseList.originalLineOfText;
  var s = debugConsoleEntryIntellisenseList.currentWord;
  var a = debugConsoleEntryIntellisenseList.currentCaretPos;
  if (i.charAt(0) == "_") i = "[" + i + "]";
  var l = false;
  if (
    n.t === CompletionKindEnumSuggestedPrefix ||
    n.t === CompletionKindFolder
  ) {
    i += ".";
    l = true;
  }
  var d = false;
  if (n.t == CompletionKindFunction || n.t == CompletionKindEvent) {
    d = true;
  }
  if (n.isExactMatch && t && !d && !l) {
    i += "\t";
  }
  if (o) {
    i += o;
    l = true;
  }
  var c = r.substr(0, a) + i + r.substr(a + s.length);
  var u = 0;
  if (d) {
    c += "()";
    u += 1;
    l = true;
  }
  editor.pushUndoStop();
  editor.executeEdits("isense", [
    {
      range: new monaco.Range(
        debugConsoleEntryIntellisenseList.originalLineNumber,
        1,
        debugConsoleEntryIntellisenseList.originalLineNumber,
        99999999
      ),
      text: c,
    },
  ]);
  editor.setSelection({
    startLineNumber: debugConsoleEntryIntellisenseList.originalLineNumber,
    startColumn: a + i.length + u + 1,
    endLineNumber: debugConsoleEntryIntellisenseList.originalLineNumber,
    endColumn: a + i.length + u + 1,
  });
  editor.focus();
  if (l) {
    triggerIntellisense();
  }
  return true;
}
function toggleSigHelp(e) {
  var t = document.getElementsByClassName("sigHelpText")[0];
  var o = document.getElementsByClassName("sigHelpHeaderFoldIcon")[0];
  sigHelpIsExpanded = !sigHelpIsExpanded;
  if (sigHelpIsExpanded) {
    t.innerHTML = currentSigHelpExpandedHtml;
    o.classList.remove("codicon-fold-up");
    o.classList.add("codicon-fold-down");
  } else {
    t.innerHTML = currentSigHelpCollapsedHtml;
    o.classList.remove("codicon-fold-down");
    o.classList.add("codicon-fold-up");
  }
  isClickOnSigHelpToggle = true;
  setTimeout(() => {
    isClickOnSigHelpToggle = false;
  }, 250);
  e.stopPropagation();
  e.preventDefault();
  return false;
}
function sigHelpClick(e) {
  isClickOnSigHelpToggle = true;
  setTimeout(() => {
    isClickOnSigHelpToggle = false;
  }, 250);
}
function triggerIntellisense(e, t) {
  var o = document.body.getElementsByClassName(
    "cursor monaco-mouse-cursor-text"
  )[0];
  var n = o.getBoundingClientRect();
  var i = editor.getPosition();
  var r = editor.getModel().getLineContent(i.lineNumber);
  debugConsoleIntellisenseRequestId++;
  var s = debugConsoleIntellisenseRequestId;
  debugConsoleEntryIntellisenseList.onHeightTooLarge = (e) => {
    if (s == debugConsoleIntellisenseRequestId) {
      let t = debugConsoleEntryContainer.getBoundingClientRect();
      debugConsoleEntryIntellisenseBox.style.height = e + "px";
      debugConsoleEntryIntellisenseList.setShowScrollbarV(false);
    }
  };
  debugConsoleEntryIntellisenseList.onClickItem = (e) => {
    handleSelectedDebugConsoleIntellisenseEntryMonaco(e.index);
  };
  getLiveDebugIntellisenseMonaco(
    { expr: r, caret: i.column, lineNumber: i.lineNumber },
    e,
    t,
    (e, t, o, a, l) => {
      if (s !== debugConsoleIntellisenseRequestId) {
        return;
      }
      debugConsoleEntryIntellisenseListItemSelectedIndex = -1;
      debugConsoleEntryIntellisenseBox.style.height = "200px";
      debugConsoleEntryIntellisenseList.setShowScrollbarV(true);
      debugConsoleEntryIntellisenseList.setItemCount(0);
      debugConsoleEntryIntellisenseList.resetScrollPosition();
      debugConsoleEntryIntellisenseList.lazyRequestId = l;
      debugConsoleEntryIntellisenseList.pendingLazyCompletions = [];
      debugConsoleEntryIntellisenseList.originalLineNumber = i.lineNumber;
      debugConsoleEntryIntellisenseList.originalLineOfText = r;
      debugConsoleEntryIntellisenseList.currentWord = e;
      debugConsoleEntryIntellisenseList.currentCaretPos = t;
      if (o.length == 0) {
        debugConsoleEntryIntellisenseBox.style.display = "none";
      } else {
        debugConsoleEntryIntellisenseBox.style.display = "block";
        debugConsoleEntryIntellisenseBox.style.height = "200px";
        if (o.length > 0) {
          o[0].isDefault = true;
          if (o[0].l.localeCompare(e, "en", { sensitivity: "base" }) === 0)
            o[0].isExactMatch = true;
        }
        debugConsoleEntryIntellisenseList.setItemCount(o.length);
        debugConsoleEntryIntellisenseList.dataNodesDATA = o;
        debugConsoleEntryIntellisenseBox.style.left = "-500px";
        debugConsoleEntryIntellisenseBox.style.display = "block";
      }
      let d = debugConsoleEntryIntellisenseBox.getBoundingClientRect();
      debugConsoleEntryIntellisenseBox.style.left = n.left + "px";
      debugConsoleEntryIntellisenseBox.style.top = n.bottom + 2 + "px";
      if (a && a.length > 0) {
        let e = document.body.getBoundingClientRect();
        debugConsoleEntryIntellisenseBoxSignature.style.left = n.left + "px";
        debugConsoleEntryIntellisenseBoxSignature.style.bottom =
          e.height - n.top + 2 + 20 + "px";
        debugConsoleEntryIntellisenseBoxSignature.style.display = "block";
        debugConsoleEntryIntellisenseBoxSignature.innerText = "";
        debugConsoleEntryIntellisenseBoxSignature.classList.remove(
          "noBoxShadow"
        );
        var c = "";
        a.forEach((e) => {
          var t = e.label;
          if (e.activeParam > 0 && e.activeParam <= e.params.length) {
            let o = e.params[e.activeParam].label[0];
            let n = e.params[e.activeParam].label[1];
            t =
              TEXTtoHTML(t.substr(0, o)) +
              "<div class='debugSigHelpActiveArg'>" +
              TEXTtoHTML(t.substr(o, n - o)) +
              "</div>" +
              TEXTtoHTML(t.substr(n));
          } else {
            t = TEXTtoHTML(t);
          }
          if (c.length) c += "<br/>";
          c += "<div class='sigHelpHeaderText'>" + t + "</div>";
        });
        debugConsoleEntryIntellisenseBoxSignature.innerHTML +=
          "<div class='sigHelpHeader'><div class='sigHelpHeaderFoldIcon codicon " +
          (sigHelpIsExpanded ? "codicon-fold-down" : "codicon-fold-up") +
          "' onclick='toggleSigHelp()' title='Fold/Collapse (F1)'></div><div class='sigHelpHeaderTextOuter'>" +
          c +
          "</div></div>";
        let t = a[0];
        var u = window.markdownit();
        var p = u.render(t.doc);
        var f = t.doc.split("\r\n");
        var g = 0;
        var m = f[g++];
        while (g < f.length && (m.charAt(0) === "#" || m.trim().length == 0)) {
          m = f[g++];
        }
        if (m.indexOf("```") === 0) {
          while (g < f.length) {
            var h = f[g++];
            m += "\r\n" + h;
            if (h.indexOf("```") === 0) break;
          }
        }
        if (m) {
          var v = u.render(m);
          currentSigHelpExpandedHtml = p;
          currentSigHelpCollapsedHtml = v;
          if (sigHelpIsExpanded) v = p;
          debugConsoleEntryIntellisenseBoxSignature.innerHTML +=
            "<div class='sigHelpText'>" + v + "</div>";
        }
      } else {
        debugConsoleEntryIntellisenseBoxSignature.style.display = "none";
      }
    }
  );
}
function initMonaco() {
  baseURL = document.getElementsByTagName("base")[0].href;
  var e = baseURL + "monaco-editor-0.35.1-pre-min/";
  let t = URL.createObjectURL(
    new Blob(
      [
        `\n                                                self.MonacoEnvironment = {\n                                                    baseUrl: '${e}'\n                                                };\n                                                importScripts('${e}vs/base/worker/workerMain.js');\n                                            `,
      ],
      { type: "text/javascript" }
    )
  );
  require.config({ paths: { vs: e + "/vs" } });
  window.MonacoEnvironment = { getWorkerUrl: () => t };
  require(["vs/editor/editor.main"], function () {
    monacoTopPosition = new monaco.Position(1, 1);
    codePanelMain = document.getElementById("codePanelMain");
    codePanel = document.getElementById("codePanel");
    createDropDowns();
    codePanelMainInner = createDOMElement(
      codePanelMain,
      "div",
      "codePanelMainInner"
    );
    codePanelMainInnerMonacoContainer = createDOMElement(
      codePanelMainInner,
      "div",
      "codePanelMainInnerMonacoContainer"
    );
    monaco.languages.register({ id: "twinbasic" });
    editor = monaco.editor.create(
      codePanelMainInnerMonacoContainer,
      {
        language: "twinbasic",
        theme: "vs-dark",
        fixedOverflowWidgets: true,
        trimAutoWhitespace: false,
        unicodeHighlight: { ambiguousCharacters: false },
        "bracketPairColorization.enabled": true,
        wordBasedSuggestions: false,
      },
      {
        textModelService: {
          createModelReference: function (e) {
            var t = fs.tree.resolvePath("twinbasic:" + e.resource.path);
            if (t.openEditorNode) {
              const e = {
                load() {
                  return Promise.resolve(e);
                },
                dispose() {},
                textEditorModel: t.openEditorNode.monacoModelInstance,
              };
              return Promise.resolve({ object: e, dispose() {} });
            }
            var o = monaco.editor.createModel("", "twinbasic");
            o.fileNode = t;
            const n = {
              load() {
                return Promise.resolve(n);
              },
              dispose() {},
              textEditorModel: o,
            };
            return new Promise((e, i) => {
              fs.readFile(t, (t, i) => {
                if (t > 0) {
                  var r = new TextDecoder().decode(i);
                  o.setValue(r);
                  e({ object: n, dispose() {} });
                }
              });
            });
          },
          registerTextModelContentProvider: () => ({ dispose: () => {} }),
        },
      }
    );
    editor.onDidBlurEditorText(onDebugConsoleEntryLostFocus);
    editor.onKeyDown((e) => {
      var t = e.browserEvent.key;
      if (e.ctrlKey || e.altKey) {
        TemporaryDisabledKeys[t] = true;
      }
      let o = debugConsoleEntryIntellisenseBox.style.display === "block";
      if (o) {
        if (t === "Escape") {
          debugConsoleEntryIntellisenseBox.style.display = "none";
          debugConsoleEntryIntellisenseBoxSignature.style.display = "none";
          e.stopPropagation();
        } else if (t === "Tab") {
          e.preventDefault();
          e.stopPropagation();
        } else if (t === "ArrowUp") {
          e.preventDefault();
          e.stopPropagation();
          handleIsenseUpKey();
        } else if (t === "ArrowDown") {
          e.preventDefault();
          e.stopPropagation();
          handleIsenseDownKey();
        } else if (t === "Enter") {
          if (debugConsoleEntryIntellisenseListItemSelectedIndex !== -1) {
            handleSelectedDebugConsoleIntellisenseEntryMonaco(
              debugConsoleEntryIntellisenseListItemSelectedIndex
            );
            e.stopPropagation();
            e.preventDefault();
            return false;
          }
        } else if (t === "Space") {
          if (debugConsoleEntryIntellisenseListItemSelectedIndex !== -1) {
            handleSelectedDebugConsoleIntellisenseEntryMonaco(
              debugConsoleEntryIntellisenseListItemSelectedIndex
            );
            return false;
          }
        }
      } else {
        var n =
          debugConsoleEntryIntellisenseBoxSignature.style.display !== "none";
        if (n) {
          if (
            t === "Escape" ||
            t === "Enter" ||
            t === "ArrowUp" ||
            t === "ArrowDown"
          ) {
            debugConsoleEntryIntellisenseBoxSignature.style.display = "none";
            e.stopPropagation();
          }
        }
      }
    });
    editor.onKeyUp((e) => {
      var t = e.browserEvent.key;
      var o = false;
      if (TemporaryDisabledKeys[e.browserEvent.key]) {
        delete TemporaryDisabledKeys[e.browserEvent.key];
        o = true;
      }
      let n = debugConsoleEntryIntellisenseBox.style.display === "block";
      if (n) {
        if (t === "ArrowUp" || t === "ArrowDown" || t === "PrintScreen") {
          return;
        } else if (t === "Tab") {
          if (debugConsoleEntryIntellisenseListItemSelectedIndex !== -1) {
            handleSelectedDebugConsoleIntellisenseEntryMonaco(
              debugConsoleEntryIntellisenseListItemSelectedIndex
            );
            e.stopPropagation();
            return false;
          } else {
            handleSelectedDebugConsoleIntellisenseEntryMonaco(0, true);
          }
        } else {
          if (debugConsoleEntryIntellisenseListItemSelectedIndex !== -1) {
            if (SpecialKeysThatAcceptSelectedIntellisense[t]) {
              handleSelectedDebugConsoleIntellisenseEntryMonaco(
                debugConsoleEntryIntellisenseListItemSelectedIndex,
                false,
                t
              );
              return;
            }
          }
        }
      } else {
        if (e.code === "Space" && e.ctrlKey) {
          triggerIntellisense(false, true);
          return;
        }
      }
      if (e.ctrlKey) return;
      if (e.altKey) return;
      if (t.length > 1) {
        if (SpecialKeysThatCloseIntellisense[t]) {
          if (n) {
            debugConsoleEntryIntellisenseBox.style.display = "none";
            debugConsoleEntryIntellisenseBoxSignature.style.display = "none";
          }
          return;
        }
      }
      var i = false;
      if (t === "!") {
        if (n) {
          debugConsoleEntryIntellisenseBox.style.display = "none";
          debugConsoleEntryIntellisenseBoxSignature.style.display = "none";
        }
        return;
      } else if (t === "Backspace") {
        if (!n) {
          return;
        }
        i = true;
      } else if (t.length > 1 || KeysThatDontTriggerIntellisense[t]) {
        return;
      }
      if (liveIDEOptions["intellisenseMode"] !== "MODERN") {
        if (liveIDEOptions["intellisenseMode"] === "LEGACY") {
          if (!n && !LegacyKeysThatTriggerIntellisense[t]) {
            return;
          }
        } else {
          let e =
            debugConsoleEntryIntellisenseBoxSignature.style.display === "block";
          if (!n && !e) {
            return;
          }
        }
      }
      if (o) {
        return;
      }
      triggerIntellisense(i);
    });
    monaco.editor.addKeybindingRules([
      { keybinding: monaco.KeyCode.F1, command: null },
    ]);
    editor.addAction({
      id: "tbCut",
      label: "剪切",
      keybindings: [
        monaco.KeyMod.chord(monaco.KeyMod.CtrlCmd | monaco.KeyCode.KeyX),
      ],
      precondition: null,
      keybindingContext: "textInputFocus",
      contextMenuGroupId: "9_cutcopypaste",
      contextMenuOrder: 0.9,
      run: function (e) {
        cutOrCopy(e, true);
      },
    });
    editor.addAction({
      id: "tbCopy",
      label: "复制",
      keybindings: [
        monaco.KeyMod.chord(monaco.KeyMod.CtrlCmd | monaco.KeyCode.KeyC),
      ],
      precondition: null,
      keybindingContext: "textInputFocus",
      contextMenuGroupId: "9_cutcopypaste",
      contextMenuOrder: 0.91,
      run: function (e) {
        cutOrCopy(e, false);
      },
    });
    editor.addAction({
      id: "tbPaste",
      label: "粘贴",
      keybindings: [
        monaco.KeyMod.chord(monaco.KeyMod.CtrlCmd | monaco.KeyCode.KeyV),
      ],
      precondition: null,
      keybindingContext: "textInputFocus",
      contextMenuGroupId: "9_cutcopypaste",
      contextMenuOrder: 0.92,
      run: function (e) {
        if (!e.hasTextFocus()) return;
        editorPaste(e);
      },
    });
    editor.addAction({
      id: "tbPasteAsComment",
      label: "粘贴为注释",
      keybindings: [
        monaco.KeyMod.chord(
          monaco.KeyMod.CtrlCmd | monaco.KeyMod.Alt | monaco.KeyCode.KeyV
        ),
      ],
      precondition: null,
      keybindingContext: "textInputFocus",
      contextMenuGroupId: "9_cutcopypaste",
      contextMenuOrder: 0.92,
      run: function (e) {
        if (!e.hasTextFocus()) return;
        editorPaste(e, true);
      },
    });
    editor.addAction({
      id: "tbGoToDefinition",
      label: "转到定义",
      keybindings: [
        monaco.KeyMod.chord(monaco.KeyMod.Shift | monaco.KeyCode.F2),
        monaco.KeyCode.F12,
      ],
      precondition: null,
      keybindingContext: null,
      contextMenuGroupId: "navigation",
      contextMenuOrder: 1,
      run: function (e) {
        var t = e.getModel();
        updateLastPosition(
          t.fileNode.getFullPath(),
          e.getPosition().lineNumber
        );
        editor.trigger("twinbasic", "editor.action.goToTypeDefinition");
      },
    });
    let e = require("vs/platform/actions/common/actions").MenuRegistry
      ._menuItems;
    let t = [...e].find((e) => e[0].id == "EditorContext");
    let o = t[1];
    let n = [
      "editor.action.goToTypeDefinition",
      "editor.action.clipboardCopyAction",
      "editor.action.clipboardCutAction",
      "editor.action.clipboardPasteAction",
    ];
    setTimeout(() => {
      let e = (e, t) => {
        let o = e._first;
        do {
          let n = t.includes(o.element?.command?.id);
          if (n) {
            e._remove(o);
          }
        } while ((o = o.next));
      };
      e(o, n);
    }, 5e3);
    editor.addAction({
      id: "tbToggleBookmark",
      label: "切换书签",
      keybindings: [
        monaco.KeyMod.chord(monaco.KeyMod.CtrlCmd | monaco.KeyCode.KeyB),
      ],
      precondition: null,
      keybindingContext: null,
      contextMenuGroupId: "navigation",
      contextMenuOrder: 1.1,
      run: function (e) {
        var t = e.getModel();
        toggleBookmark(t.fileNode.getFullPath(), e.getPosition().lineNumber);
      },
    });
    editor.addAction({
      id: "tbNextBookmark",
      label: "下一个书签",
      keybindings: [
        monaco.KeyMod.chord(monaco.KeyMod.CtrlCmd | monaco.KeyCode.KeyN),
      ],
      precondition: null,
      keybindingContext: null,
      contextMenuGroupId: "navigation",
      contextMenuOrder: 1.2,
      run: function (e) {
        var t = e.getModel();
        gotoNextBookmark(t.fileNode.getFullPath(), e.getPosition().lineNumber);
      },
    });
    editor.addAction({
      id: "tbPrevBookmark",
      label: "上一个书签",
      keybindings: [
        monaco.KeyMod.chord(monaco.KeyMod.CtrlCmd | monaco.KeyCode.KeyM),
      ],
      precondition: null,
      keybindingContext: null,
      contextMenuGroupId: "navigation",
      contextMenuOrder: 1.3,
      run: function (e) {
        var t = e.getModel();
        gotoPrevBookmark(t.fileNode.getFullPath(), e.getPosition().lineNumber);
      },
    });
    editor.addAction({
      id: "tbClearBookmarks",
      label: "清除所有书签(文档)",
      precondition: null,
      keybindingContext: null,
      contextMenuGroupId: "navigation",
      contextMenuOrder: 1.4,
      run: function (e) {
        var t = e.getModel();
        clearAllBookmarks(t.fileNode.getFullPath(), false);
      },
    });
    editor.addAction({
      id: "tbClearBookmarksProject",
      label: "清除所有书签(项目)",
      precondition: null,
      keybindingContext: null,
      contextMenuGroupId: "navigation",
      contextMenuOrder: 1.4,
      run: function (e) {
        var t = e.getModel();
        clearAllBookmarks(t.fileNode.getFullPath(), true);
      },
    });
    editor.addAction({
      id: "tbFind",
      label: "在页面中查找...",
      keybindings: [
        monaco.KeyMod.chord(monaco.KeyMod.CtrlCmd | monaco.KeyCode.KeyF),
      ],
      precondition: null,
      keybindingContext: null,
      run: function (e) {
        var t = e.getModel();
        const o = e.getAction("actions.find");
        o.run();
        var n = editor.getSelection();
        if (n.startLineNumber != n.endLineNumber) {
          if (n.endColumn == 1) {
            n.endLineNumber -= 1;
            n.endColumn = 9999999999999;
          }
          selectionText = editor.getModel().getValueInRange(n);
          if (selectionText.length > 0) {
            const e = editor.getContribution("editor.contrib.findController");
            e.setSearchString(selectionText);
            var i = e._widget._domNode.querySelector(".input");
            var r = new Event("input");
            i.dispatchEvent(r);
          }
        }
      },
    });
    editor.addAction({
      id: "tbFindReplace",
      label: "在页面中查找和替换...",
      keybindings: [
        monaco.KeyMod.chord(monaco.KeyMod.CtrlCmd | monaco.KeyCode.KeyH),
      ],
      precondition: null,
      keybindingContext: null,
      run: function (e) {
        var t = e.getModel();
        const o = e.getAction("editor.action.startFindReplaceAction");
        o.run();
        var n = editor.getSelection();
        if (n.startLineNumber != n.endLineNumber) {
          if (n.endColumn == 1) {
            n.endLineNumber -= 1;
            n.endColumn = 9999999999999;
          }
          selectionText = editor.getModel().getValueInRange(n);
          if (selectionText.length > 0) {
            const e = editor.getContribution("editor.contrib.findController");
            e.setSearchString(selectionText);
            var i = e._widget._domNode.querySelector(".input");
            var r = new Event("input");
            i.dispatchEvent(r);
          }
        }
      },
    });
    editor.addAction({
      id: "tbLastPosition",
      label: "上次位置",
      keybindings: [
        monaco.KeyMod.chord(
          monaco.KeyMod.CtrlCmd | monaco.KeyMod.Shift | monaco.KeyCode.F2
        ),
      ],
      contextMenuGroupId: "navigation",
      contextMenuOrder: 1.1,
      precondition: null,
      keybindingContext: null,
      run: function (e) {
        var t = undefined;
        var o = undefined;
        do {
          o = lastPositions.pop();
          t = fs.tree.resolvePath("twinbasic:" + o.path);
        } while (!t);
        if (t) {
          openEditors.openFile(t, false, false, false, o.lineStart, 1);
        }
      },
    });
    let { widget: i } = editor.getContribution(
      "editor.contrib.suggestController"
    );
    if (i) {
      const e = i.value;
      if (e && e._setDetailsVisible) {
        e._setDetailsVisible(true);
      }
      if (e && e._persistedSize) {
      }
    }
    editor.addCommand(monaco.KeyMod.CtrlCmd | monaco.KeyCode.UpArrow, () => {
      var e = editor.getPosition();
      var t = findClosestOutlinePanelItem(
        outlinePanel.cachedSymbols,
        e.lineNumber - 1,
        false
      );
      if (t) {
        revealLineInEditor(t.range.start.line + 1, 1, true);
      }
    });
    editor.addCommand(monaco.KeyMod.CtrlCmd | monaco.KeyCode.DownArrow, () => {
      var e = editor.getPosition();
      var t = findClosestOutlinePanelItem(
        outlinePanel.cachedSymbols,
        e.lineNumber,
        true
      );
      if (t) {
        revealLineInEditor(t.range.start.line + 1, 1, true);
      }
    });
    registerCommands();
    codePanelMain.addEventListener("mouseup", (e) => {
      if (e.button == 3) {
        editor.trigger("twinbasic", "tbLastPosition");
      }
    });
    monaco.languages.setLanguageConfiguration("twinbasic", {
      comments: { lineComment: "'" },
      brackets: [
        ["{", "}"],
        ["[", "]"],
        ["(", ")"],
      ],
      autoClosingPairs: [
        { open: "{", close: "}" },
        { open: "[", close: "]" },
        { open: "(", close: ")" },
        { open: '"', close: '"', notIn: ["string"] },
      ],
      indentationRules: {
        increaseIndentPattern:
          "^\\s*([pP][uU][bB][lL][iI][cC]\\s)?([pP][rR][iI][vV][aA][tT][eE]\\s)?([fF][rR][iI][eE][nN][dD]\\s)?(([sS][uU][bB]\\s)|([fF][uU][nN][cC][tT][iI][oO][nN]\\s)|([pP][rR][oO][pP][eE][rR][tT][yY]\\s)|([mM][oO][dD][uU][lL][eE]\\s)|([cC][lL][aA][sS][sS]\\s)|([iI][nN][tT][eE][rR][fF][aA][cC][eE]\\s)|([tT][yY][pP][eE]\\s)|([eE][nN][uU][mM]\\s)|([iI][fF]\\s)|([eE][lL][sS][eE][iI][fF]\\s)|([eE][lL][sS][eE]\\s*('.*)?$)|([fF][oO][rR]\\s)|([wW][hH][iI][lL][eE]\\s)|([dD][oO]\\s)|([sS][eE][lL][eE][cC][tT]\\s)).*",
        decreaseIndentPattern:
          "^\\s*(([eE][lL][sS][eE]$)|([eE][lL][sS][eE][iI][fF]\\s.*$)|([eE][nN][dD]\\s+.*$)|([nN][eE][xX][tT]$)|([nN][eE][xX][tT]\\s.*$)|([wW][eE][nN][dD]$)|([wW][eE][nN][dD]\\s.*$)|([lL][oO][oO][pP]$)|([lL][oO][oO][pP]\\s.*$))",
      },
    });
    monaco.editor.defineTheme("twinbasic-dark", {
      base: "vs-dark",
      inherit: true,
      rules: [],
      colors: { "editor.lineHighlightBackground": "#303030" },
    });
    monaco.editor.defineTheme("twinbasic-light", {
      base: "vs",
      inherit: true,
      rules: [],
      colors: { "editor.lineHighlightBackground": "#F2F2F2" },
    });
    editor.onDidLayoutChange((e) => {
      setTimeout(() => {
        var e = editor._domElement.getElementsByClassName("margin")[0];
        var t = editor._domElement.getElementsByClassName("line-numbers")[0];
        if (e.offsetWidth != editor.currentGutterWidth) {
          editor.currentGutterWidth = e.offsetWidth;
          var o = editor._domElement;
          o.style.setProperty(
            "--monacoGutterWidth",
            editor.currentGutterWidth.toString()
          );
          o.style.setProperty(
            "--monacoFontFamily",
            window.getComputedStyle(t).fontFamily
          );
          o.style.setProperty(
            "--monacoFontSize",
            window.getComputedStyle(t).fontSize
          );
        }
      }, 0);
    });
    editor.onDidChangeModelContent(() => trackAddinWidgetMovements(editor));
    const r = editor._codeEditorService;
    const s = r.openCodeEditor.bind(r);
    r.openCodeEditor = async (e, t) => {
      var o = fs.tree.resolvePath("twinbasic:" + e.resource.path);
      openEditors.openFile(
        o,
        false,
        false,
        false,
        e.options.selection.startLineNumber,
        e.options.selection.startColumn,
        true
      );
    };
    editor.onDidScrollChange((e) => {
      if (debugConsoleEntryIntellisenseBox) {
        debugConsoleEntryIntellisenseBox.style.display = "none";
        debugConsoleEntryIntellisenseBoxSignature.style.display = "none";
      }
      syncVisibleSemanticTokens();
    });
    editor.onMouseMove((e) => {
      if (glyphMouseDownTimer) {
        if (e.target.position.lineNumber !== activeBreakLineNumber) {
          clearTimeout(glyphMouseDownTimer);
          glyphMouseDownTimer = undefined;
        }
      }
      if (glyphMouseDragging) {
        hoverBreakpoints = editor.deltaDecorations(hoverBreakpoints, [
          {
            range: new monaco.Range(
              e.target.position.lineNumber,
              1,
              e.target.position.lineNumber,
              1
            ),
            options: {
              isWholeLine: true,
              glyphMarginClassName: "marginGlyph breakingGlyphDrag",
            },
          },
        ]);
        return;
      }
      const t = 2;
      if (e.target.type !== t) {
        hoverBreakpoints = editor.deltaDecorations(hoverBreakpoints, []);
        return;
      }
      if (e.target.position.lineNumber !== activeBreakLineNumber) {
        hoverBreakpoints = editor.deltaDecorations(hoverBreakpoints, [
          {
            range: new monaco.Range(
              e.target.position.lineNumber,
              1,
              e.target.position.lineNumber,
              1
            ),
            options: {
              isWholeLine: true,
              glyphMarginClassName: "marginGlyph breakpointInactiveGlyph",
            },
          },
        ]);
      } else {
        hoverBreakpoints = editor.deltaDecorations(hoverBreakpoints, []);
      }
    });
    editor.onMouseDown((e) => {
      const t = 2;
      if (e.target.type === t) {
        if (activeBreakLineNumber === e.target.position.lineNumber) {
          glyphMouseDownTimer = setTimeout(startGlyphDrag, 200);
          return;
        }
        toggleBreakpointAtLine(e.target.position.lineNumber);
      }
      onDebugConsoleEntryLostFocus(e);
    });
    editor.onMouseLeave((e) => {
      if (glyphMouseDragging) {
        cancelGlyphDrag();
      }
    });
    editor.onMouseUp((e) => {
      if (glyphMouseDragging) {
        cancelGlyphDrag();
        setCurrentThreadExecutionPoint(e.target.position.lineNumber);
      }
      if (glyphMouseDownTimer) {
        clearTimeout(glyphMouseDownTimer);
        const t = 2;
        if (e.target.type === t) {
          if (activeBreakLineNumber === e.target.position.lineNumber) {
            toggleBreakpointAtLine(e.target.position.lineNumber);
          }
        }
      }
    });
    var a = document.getElementById("lineNum");
    var l = document.getElementById("columnNum");
    statusLineCol = document.getElementById("statusLineCol");
    memUsageDiv = document.getElementById("memUsage");
    userObjectsDiv = document.getElementById("userObjects");
    gdiObjectsDiv = document.getElementById("gdiObjects");
    statusMemUsageDiv = document.getElementById("statusMemUsage");
    editor.onDidChangeCursorPosition((e) => {
      if (a.innerText != e.position.lineNumber) {
        if (openEditors.selectedEditorNode.pendingLineEdits.length > 0) {
          openEditors.selectedEditorNode.pendingLineEdits.forEach((e) => {
            if (e.range.start.line + 1 == a.innerText) {
              if (
                e.docVersion ===
                openEditors.selectedEditorNode.fileNode.ideVersionId
              ) {
                var t = {
                  range: new monaco.Range(
                    e.range.start.line + 1,
                    e.range.start.character + 1,
                    e.range.end.line + 1,
                    e.range.end.character + 1
                  ),
                  text: e.newText,
                  forceMoveMarkers: true,
                };
                if (e.noUndo) {
                  var o =
                    openEditors.selectedEditorNode.monacoModelInstance._undoRedoService._editStacks.get(
                      openEditors.selectedEditorNode.monacoModelInstance.uri
                        ._formatted
                    );
                  var n = o._past.length;
                  var i = n - 1;
                  editor.executeEdits("twinbasic", [t]);
                  if (i >= 0) {
                    var r = o._past[i].groupId;
                    if (r === 0) {
                      globalUndoStackGroupId++;
                      r = globalUndoStackGroupId;
                    }
                    while (i < o._past.length) {
                      o._past[i].groupId = r;
                      i++;
                    }
                  }
                } else {
                  editor.executeEdits("twinbasic", [t]);
                }
              }
            }
          });
          openEditors.selectedEditorNode.pendingLineEdits = [];
        }
        a.innerText = e.position.lineNumber;
      }
      l.innerText = e.position.column;
      codeComboSelectors.changedDocumentPosition(e.position.lineNumber);
    });
    monaco.languages.registerHoverProvider("twinbasic", {
      provideHover: function (e, t) {
        if (activeDebuggingFrameId) {
          var o = undefined;
          var n = undefined;
          var i = undefined;
          var r = editor.getSelection();
          var s = undefined;
          if (r.containsPosition(t)) {
            s = e.getValueInRange(r);
            if (s.length == 0) {
              s = undefined;
            }
          }
          if (s) {
            o = s;
            n = r.startColumn;
            i = r.endColumn;
          } else {
            var a = e.getWordAtPosition(t);
            n = a.startColumn;
            i = a.endColumn;
            var l = 0;
            var d = false;
            while (1) {
              var c = e.getValueInRange(
                new monaco.Range(t.lineNumber, n - 1, t.lineNumber, n)
              );
              if (d || c == "." || c == "!") {
                d = false;
                c = e.getValueInRange(
                  new monaco.Range(t.lineNumber, n - 2, t.lineNumber, n - 1)
                );
                a = e.getWordAtPosition(
                  new monaco.Position(t.lineNumber, n - 2)
                );
                if (!a || c == ")") {
                  if (c == ")") {
                    n -= 2;
                    l++;
                    var u = false;
                    while (l) {
                      if (n == 0) break;
                      c = e.getValueInRange(
                        new monaco.Range(t.lineNumber, n - 1, t.lineNumber, n)
                      );
                      if (u) {
                        if (c == '"') {
                          var p = e.getValueInRange(
                            new monaco.Range(
                              t.lineNumber,
                              n - 2,
                              t.lineNumber,
                              n - 1
                            )
                          );
                          if (p == '"') {
                            n--;
                          } else {
                            u = false;
                          }
                        }
                      } else {
                        if (c == ")") {
                          l++;
                        } else if (c == "(") {
                          l--;
                        } else if (c == '"') {
                          u = true;
                        }
                      }
                      n--;
                    }
                    n++;
                    d = true;
                  } else {
                    n--;
                    break;
                  }
                } else {
                  n = a.startColumn;
                }
              } else {
                break;
              }
            }
            var f = t.lineNumber;
            var g = e.getValueInRange(new monaco.Range(f, i, f, i + 1));
            if (g === "(") {
              var m = i + 1;
              var u = false;
              var l = 1;
              var h;
              while (1) {
                var v = e.getValueInRange(new monaco.Range(f, m, f, m + 1));
                if (u) {
                  if (v === '"') {
                    u = false;
                  }
                } else {
                  if (v === '"') {
                    u = true;
                  } else {
                    if (v === "(") {
                      l++;
                    } else if (v === ")") {
                      l--;
                      if (l == 0) {
                        i = m + 1;
                        break;
                      }
                    }
                  }
                }
                if (v.length == 0) {
                  if (h === "_") {
                    f++;
                    i = 1;
                    m = 1;
                  } else {
                    break;
                  }
                }
                if (v !== " " && v !== "\t") {
                  h = v;
                }
                m++;
              }
            }
            o = e.getValueInRange(new monaco.Range(t.lineNumber, n, f, i));
          }
          return new Promise((e, r) => {
            debugSocket.request(
              "evaluate",
              {
                expression: o,
                context: "hover",
                frameId: activeDebuggingFrameId,
              },
              (r) => {
                if (r.success) {
                  var s = r.body.result;
                  let a = "<span style='color:#c586c0;'>" + TEXTtoHTML(o) + "";
                  a += ":</span> &nbsp; ";
                  a += TEXTtoHTML(s.value);
                  if (s.fields) {
                    a += "<hr/>";
                    s.fields.forEach((e) => {
                      a +=
                        "<br/>&nbsp; &nbsp; &nbsp; &nbsp;<span style='color:#c586c0;'>";
                      a += e.name;
                      a += ":</span> &nbsp; ";
                      a += e.value;
                    });
                  }
                  e({
                    range: {
                      startColumn: n,
                      startLineNumber: t.lineNumber,
                      endColumn: i,
                      endLineNumber: t.lineNumber,
                    },
                    contents: [{ supportHtml: true, value: a }],
                  });
                } else {
                  let s = "<span style='color:#c586c0;'>" + TEXTtoHTML(o) + "";
                  s += ":</span> &nbsp; ";
                  s += TEXTtoHTML(r.message);
                  e({
                    range: {
                      startColumn: n,
                      startLineNumber: t.lineNumber,
                      endColumn: i,
                      endLineNumber: t.lineNumber,
                    },
                    contents: [{ supportHtml: true, value: s }],
                  });
                }
              }
            );
          });
        }
        var y = "twinbasic:" + e.fileNode.getFullPath();
        return new Promise((e, o) => {
          lspSocket.request(
            "textDocument/hover",
            {
              textDocument: { uri: y },
              position: { line: t.lineNumber - 1, character: t.column - 1 },
            },
            (t) => {
              if (t.result) {
                e({
                  range: {
                    startColumn: t.result.range.start.character + 1,
                    startLineNumber: t.result.range.start.line + 1,
                    endColumn: t.result.range.start.character + 1,
                    endLineNumber: t.result.range.start.line + 1,
                  },
                  contents: [
                    { value: t.result.contents.value + "\r\n#  \r\n#  \r\n" },
                  ],
                });
              } else {
                e(null);
              }
            }
          );
        });
      },
    });
    monaco.languages.registerFoldingRangeProvider("twinbasic", {
      provideFoldingRanges: function (e, t, o) {
        if (!e.fileNode) return null;
        var n = "twinbasic:" + e.fileNode.getFullPath();
        return new Promise((e, t) => {
          lspSocket.request(
            "textDocument/foldingRange",
            { textDocument: { uri: n } },
            (t) => {
              if (t.result) {
                var o = [];
                t.result.forEach((e) => {
                  o.push({
                    start: e.startLine + 1,
                    end: e.endLine + 1,
                    kind: monaco.languages.FoldingRangeKind.Comment,
                  });
                });
                cachedFoldingRanges = o;
                syncVisibleSemanticTokens();
                e(o);
              } else {
                e(null);
              }
            }
          );
        });
      },
    });
    monaco.languages.registerTypeDefinitionProvider("twinbasic", {
      provideTypeDefinition: function (e, t, o) {
        var n = "twinbasic:" + e.fileNode.getFullPath();
        return new Promise((e, o) => {
          lspSocket.request(
            "textDocument/definition",
            {
              textDocument: { uri: n },
              position: { line: t.lineNumber - 1, character: t.column - 1 },
            },
            (t) => {
              if (t.result) {
                e({
                  range: new monaco.Range(
                    t.result.range.start.line + 1,
                    t.result.range.start.character + 1,
                    t.result.range.end.line + 1,
                    t.result.range.end.character + 1
                  ),
                  uri: monaco.Uri.parse(t.result.uri),
                });
              } else {
                e(null);
              }
            }
          );
        });
      },
    });
    monaco.languages.registerRenameProvider("twinbasic", {
      provideRenameEdits: function (e, t, o, n) {
        var i = "twinbasic:" + e.fileNode.getFullPath();
        return new Promise((e, n) => {
          lspSocket.request(
            "textDocument/rename",
            {
              textDocument: { uri: i },
              position: { line: t.lineNumber - 1, character: t.column - 1 },
              newName: o,
            },
            (t) => {
              alert("需要在这里进行大量编辑...");
              debugger;
              e(null);
            }
          );
        });
      },
      resolveRenameLocation123: function (e, t, o) {
        debugger;
      },
    });
    if (0)
      monaco.languages.registerSignatureHelpProvider("twinbasic", {
        signatureHelpTriggerCharacters: ["(", ",", " "],
        provideSignatureHelp: function (e, t) {
          var o = "twinbasic:" + e.fileNode.getFullPath();
          return new Promise((e, n) => {
            lspSocket.request(
              "textDocument/signatureHelp",
              {
                textDocument: { uri: o },
                position: { line: t.lineNumber - 1, character: t.column - 1 },
              },
              (t) => {
                if (t.result) {
                  e({ value: t.result, dispose: () => {} });
                } else {
                  e(null);
                }
              }
            );
          });
        },
      });
    createPsuedoCompletionProvider();
    new ResizeObserver(changedSize).observe(document.body);
  });
}
function createPsuedoCompletionProvider() {
  if (0)
    psuedoCompletionProvider = monaco.languages.registerCompletionItemProvider(
      "twinbasic",
      {
        triggerCharacters: [".", " ", "(", "=", ",", "+", "-"],
        provideCompletionItems: function (e, t, o) {
          if (liveIDEOptions["manualIntellisense"])
            return { incomplete: false, suggestions: [] };
          var n = "twinbasic:" + e.fileNode.getFullPath();
          currentCompletionProviderRequest++;
          var i = currentCompletionProviderRequest;
          var r = e.getValueInRange(
            new monaco.Range(t.lineNumber, t.column - 1, t.lineNumber, t.column)
          );
          var s = r;
          if (!this.triggerCharacters.includes(s)) {
            s = undefined;
          }
          if (!creatingRealCompletionProvider) {
            if (realCompletionProvider) {
              var a = realCompletionProvider;
              realCompletionProvider = undefined;
              a.dispose();
              return { incomplete: true, suggestions: [] };
            } else {
              getRealCompletionResults(n, t, s, i);
            }
          } else {
            if (realCompletionProviderHasExactMatch) {
              if (s) {
                return { incomplete: true, suggestions: [] };
              } else {
                return {
                  incomplete: true,
                  suggestions: [{ label: "⁇", insertText: "" }],
                };
              }
            } else {
            }
          }
          try {
            var l = e.getWordAtPosition(t).word;
            return {
              incomplete: true,
              suggestions: [
                {
                  label: l,
                  kind: monaco.languages.CompletionItemKind.Function,
                  insertText: l,
                },
              ],
            };
          } catch (e) {
            return {
              incomplete: true,
              suggestions: [{ label: " ", insertText: "" }],
            };
          }
        },
      }
    );
}
function getRealCompletionResults(e, t, o, n) {
  lspSocket.request(
    "textDocument/completion",
    {
      textDocument: { uri: e },
      position: { line: t.lineNumber - 1, character: t.column - 1 },
      context: o ? { triggerCharacter: o } : {},
    },
    (e) => {
      if (e.result) {
        if (currentCompletionProviderRequest !== n) return;
        creatingRealCompletionProvider = true;
        realCompletionProviderHasExactMatch = e.result.exactMatchFound;
        let t = 0;
        realCompletionProvider =
          monaco.languages.registerCompletionItemProvider("twinbasic", {
            provideCompletionItems: (o, n) => {
              if (t++ > 0) return null;
              e.result.items.forEach((e) => {
                if (!e.insertText) e.insertText = e.label;
                if (e.kind >= 0 && e.kind <= 23) {
                  e.kind = suggestionFixUp[e.kind];
                }
              });
              return {
                incomplete: liveIDEOptions["manualIntellisense"] ? false : true,
                suggestions: e.result.items,
              };
            },
            resolveCompletionItem: (e, t) =>
              new Promise((t, o) => {
                lspSocket.request(
                  "completionItem/resolve",
                  { data: e.data },
                  (e) => {
                    t(e.result);
                  }
                );
              }),
          });
        if (liveIDEOptions["manualIntellisense"]) {
          editor.trigger("", "editor.action.triggerSuggest", {});
        }
        creatingRealCompletionProvider = false;
      } else {
      }
    }
  );
}
var msgBox1;
var msgBox1text;
var closeMsgBox1;
var msgBox1Extra;
var msgBox1Copy;
var msgBox2;
var msgBox2Text;
var closeMsgBox2;
var msgBox2Extra;
var msgBox2Copy;
var msgBox3;
var msgBox3Text;
var closeMsgBox3;
var msgBox3Extra;
var msgBox3Copy;
function initMsgBox() {
  msgBox1 = document.getElementById("msgBoxInner1");
  msgBox1text = document.getElementById("msgBox1text");
  closeMsgBox1 = document.getElementById("closeMsgBox1");
  msgBox1Extra = document.getElementById("msgBox1Extra");
  msgBox1Copy = document.getElementById("msgBox1Copy");
  msgBox2 = document.getElementById("msgBoxInner2");
  msgBox2text = document.getElementById("msgBox2text");
  closeMsgBox2 = document.getElementById("closeMsgBox2");
  msgBox2Extra = document.getElementById("msgBox2Extra");
  msgBox2Copy = document.getElementById("msgBox2Copy");
  msgBox3 = document.getElementById("msgBoxInner3");
  msgBox3text = document.getElementById("msgBox3text");
  closeMsgBox3 = document.getElementById("closeMsgBox3");
  msgBox3Extra = document.getElementById("msgBox3Extra");
  msgBox3Copy = document.getElementById("msgBox3Copy");
  msgBox1.onclick = msgBox1Click;
  msgBox2.onclick = msgBox2Click;
  msgBox3.onclick = msgBox3Click;
  msgBox1text.closeAction = msgBox1Close;
  msgBox2text.closeAction = msgBox2Close;
  msgBox3text.closeAction = msgBox3Close;
  closeMsgBox1.onclick = msgBox1Close;
  closeMsgBox2.onclick = msgBox2Close;
  closeMsgBox3.onclick = msgBox3Close;
  msgBox1Copy.onclick = msgBox1CopyClick;
  msgBox2Copy.onclick = msgBox2CopyClick;
  msgBox3Copy.onclick = msgBox3CopyClick;
}
function checkMsgBoxesTimeout() {
  var e = Date.now();
  if (msgBox3.style.display != "none" && e - msgBox3text.timeShown > 6e4)
    msgBox3Close();
  if (msgBox2.style.display != "none" && e - msgBox2text.timeShown > 6e4)
    msgBox2Close();
  if (msgBox1.style.display != "none" && e - msgBox1text.timeShown > 6e4)
    msgBox1Close();
}
function msgBox1Click(e) {
  msgBox1text.timeShown = Date.now();
  if (msgBox1text.style.whiteSpace == "nowrap") {
    msgBox1text.style.whiteSpace = "pre-wrap";
    msgBox1Extra.style.display = "block";
  } else {
    msgBox1text.style.whiteSpace = "nowrap";
    msgBox1Extra.style.display = "none";
  }
  layoutMsgBoxes();
  e.stopPropagation();
}
function msgBox1Close(e) {
  msgBox1text.innerHTML = msgBox2text.innerHTML ? msgBox2text.innerHTML : "";
  msgBox1text.buttonsCallback = msgBox2text.buttonsCallback;
  msgBox1text.timeShown = msgBox2text.timeShown;
  msgBox1text.style.whiteSpace = msgBox2text.style.whiteSpace;
  msgBox1.style.display = msgBox2.style.display;
  msgBox1Extra.style.display = msgBox2Extra.style.display;
  msgBox2text.innerHTML = msgBox3text.innerHTML ? msgBox3text.innerHTML : "";
  msgBox2text.buttonsCallback = msgBox3text.buttonsCallback;
  msgBox2text.timeShown = msgBox3text.timeShown;
  msgBox2text.style.whiteSpace = msgBox3text.style.whiteSpace;
  msgBox2.style.display = msgBox3.style.display;
  msgBox2Extra.style.display = msgBox3Extra.style.display;
  msgBox3.style.display = "none";
  layoutMsgBoxes();
  if (e) e.stopPropagation();
}
function msgBox1CopyClick(e) {
  copyToClipboard(msgBox1text.innerText);
  e.stopPropagation();
}
function msgBox2Click(e) {
  msgBox2text.timeShown = Date.now();
  if (msgBox2text.style.whiteSpace == "nowrap") {
    msgBox2text.style.whiteSpace = "pre-wrap";
    msgBox2Extra.style.display = "block";
  } else {
    msgBox2text.style.whiteSpace = "nowrap";
    msgBox2Extra.style.display = "none";
  }
  layoutMsgBoxes();
  e.stopPropagation();
}
function msgBox2Close(e) {
  msgBox2text.innerHTML = msgBox3text.innerHTML ? msgBox3text.innerHTML : "";
  msgBox2text.buttonsCallback = msgBox3text.buttonsCallback;
  msgBox2text.timeShown = msgBox3text.timeShown;
  msgBox2text.style.whiteSpace = msgBox3text.style.whiteSpace;
  msgBox2.style.display = msgBox3.style.display;
  msgBox2Extra.style.display = msgBox3Extra.style.display;
  msgBox3.style.display = "none";
  layoutMsgBoxes();
  if (e) e.stopPropagation();
}
function msgBox2CopyClick(e) {
  copyToClipboard(msgBox2text.innerText);
  e.stopPropagation();
}
function msgBox3Click(e) {
  msgBox3text.timeShown = Date.now();
  if (msgBox3text.style.whiteSpace == "nowrap") {
    msgBox3text.style.whiteSpace = "pre-wrap";
    msgBox3Extra.style.display = "block";
  } else {
    msgBox3text.style.whiteSpace = "nowrap";
    msgBox3Extra.style.display = "none";
  }
  layoutMsgBoxes();
  e.stopPropagation();
}
function msgBox3Close(e) {
  msgBox3.style.display = "none";
  layoutMsgBoxes();
  if (e) e.stopPropagation();
}
function msgBox3CopyClick(e) {
  copyToClipboard(msgBox3text.innerText);
  e.stopPropagation();
}
function onClickedMsgBoxButton(e) {
  e.target.parentElement.parentElement.buttonsCallback(e.target.innerText);
  e.target.parentElement.parentElement.closeAction();
  e.stopPropagation();
}
function msgBox(e, t, o) {
  e = e.toString();
  msgBox3text.innerHTML = msgBox2text.innerHTML ? msgBox2text.innerHTML : "";
  msgBox3text.buttonsCallback = msgBox2text.buttonsCallback;
  msgBox3text.timeShown = msgBox2text.timeShown;
  msgBox3text.style.whiteSpace = msgBox2text.style.whiteSpace;
  msgBox3.style.display = msgBox2.style.display;
  msgBox3Extra.style.display = msgBox2Extra.style.display;
  msgBox2text.innerHTML = msgBox1text.innerHTML ? msgBox1text.innerHTML : "";
  msgBox2text.buttonsCallback = msgBox1text.buttonsCallback;
  msgBox2text.timeShown = msgBox1text.timeShown;
  msgBox2text.style.whiteSpace = msgBox1text.style.whiteSpace;
  msgBox2.style.display = msgBox1.style.display;
  msgBox2Extra.style.display = msgBox1Extra.style.display;
  msgBox1text.innerText = e;
  if (t) {
    var n = "";
    t.forEach((e) => {
      n += '<div onclick="onClickedMsgBoxButton(event)">' + e + "</div>";
    });
    msgBox1text.innerHTML =
      "<div>" +
      msgBox1text.innerHTML +
      "</div>" +
      '<div class="inlineMsgBoxButtons">' +
      n +
      "</div>";
    msgBox1text.buttonsCallback = o;
  }
  msgBox1text.timeShown = Date.now();
  msgBox1text.style.whiteSpace = "nowrap";
  msgBox1.style.display = "inline-block";
  msgBox1Extra.style.display = "none";
  layoutMsgBoxes();
}
function layoutMsgBoxes() {
  msgBox3.style.marginTop = -(10 + msgBox3.clientHeight) + "px";
  msgBox2.style.marginTop = -(10 + msgBox2.clientHeight) + "px";
  msgBox1.style.marginTop = -(30 + msgBox1.clientHeight) + "px";
}
function showModalNotification(e, t) {
  var o = createDOMElement(undefined, "div", "simpleMsgBox", e);
  showModalDialog(o, [
    {
      caption: "确定",
      onclick: () => {
        hideModalDialog();
        if (t) t();
      },
      isDefaultCancelAction: true,
    },
  ]);
}
function doModalResult(e, t) {
  root.sendModalResultLong(e, t);
}
function showModalMsgWithButtons(e, t, o, n) {
  var i = t.split("|");
  var r = [];
  var s = 0;
  i.forEach((e) => {
    let t = s;
    r.push({
      caption: e,
      onclick: () => {
        hideModalDialog();
        doModalResult(n, t);
      },
    });
    s++;
  });
  var a = createDOMElement(undefined, "div", "simpleMsgBox", e);
  showModalDialog(a, r, o, () => {
    hideModalDialog();
    doModalResult(n, -1);
  });
}
function alertWithClipboardText(e, t) {
  var o = createDOMElement(undefined, "div", "simpleMsgBox", e);
  showModalDialog(o, [
    {
      caption: "Copy to clipboard",
      onclick: () => {
        navigator.clipboard.write([
          new ClipboardItem({
            "text/plain": new Blob([t], { type: "text/plain" }),
          }),
        ]);
        hideModalDialog();
      },
    },
    { caption: "确定", onclick: hideModalDialog, isDefaultCancelAction: true },
  ]);
}
var outlinePanelOptions = {
  showClassFields: true,
  showModuleVariables: true,
  showEnumerations: true,
  showUDTs: true,
  showDLLs: true,
  showConstructors: true,
  showProperties: true,
  showProcedures: true,
  showVariables: true,
  showParameters: true,
};
function toggleOutlineShow(e) {
  outlinePanelOptions[e.id] = outlinePanelOptions[e.id] ? false : true;
  if (outlinePanelOptions[e.id]) {
    e.iconClassDiv.classList.add("tickIcon");
    e.iconClassDiv.classList.remove("noTickIcon");
  } else {
    e.iconClassDiv.classList.remove("tickIcon");
    e.iconClassDiv.classList.add("noTickIcon");
  }
  outlinePanel.rebuildFilteredTypes();
  outlinePanel.resync();
  return true;
}
function toggleOutlineGetIconClass(e) {
  return outlinePanelOptions[e] ? "tickIcon" : "noTickIcon";
}
function initOutlinesPanel() {}
var outlinePanel = undefined;
const OUTLINEPANEL_CUSTOMPROPERTY_DETAIL = 0;
const OUTLINEPANEL_CUSTOMPROPERTY_LINENUM = 1;
const OUTLINEPANEL_CUSTOMPROPERTY_CHARNUM = 2;
const OUTLINEPANEL_CUSTOMPROPERTY_INDENTLEVEL = 3;
const _OUTLINEPANEL_CUSTOMPROPERTY_MAXCOUNT = 4;
class _outlinePanel {
  constructor(e, t) {
    var o = _OUTLINEPANEL_CUSTOMPROPERTY_MAXCOUNT;
    this.id = 0;
    this.tree = new virtualTreeView(
      e,
      "大纲",
      "twinbasic-outline:",
      false,
      o,
      "--outline",
      t
    );
    this.tree.showFolderIcons = false;
    this.tree.autoExpandOnSelect = false;
    this.tree.showTooltips = true;
    this.tree.additionalFolderClassNames = "testTree";
    this.tree.emptyFolderText = "";
    this.tree.renderDomNode = (e) => {
      var t = e.getCustomData(OUTLINEPANEL_CUSTOMPROPERTY_DETAIL);
      var o = e.getCustomData(OUTLINEPANEL_CUSTOMPROPERTY_INDENTLEVEL);
      var n = e.hasChildren();
      let i = "";
      if (n) {
        if (e.isExpanded()) {
          i =
            "<div class='outlineNodeGroupIcon iconCollapse14' onclick='toggleOutlineNode(event)'></div>";
        } else {
          i =
            "<div class='outlineNodeGroupIcon iconExpand14' onclick='toggleOutlineNode(event)'></div>";
        }
      }
      return (
        "<div class='outlineNodeItem' style='padding-left:" +
        o * 15 +
        "px'>" +
        i +
        e.getCaption() +
        (t ? "<div class='outlineNodeDetail'>" + t + "</div>" : "") +
        "</div>"
      );
    };
    this.tree.onClickNode = (e) => {
      var t = e.getCustomData(OUTLINEPANEL_CUSTOMPROPERTY_LINENUM);
      var o = e.getCustomData(OUTLINEPANEL_CUSTOMPROPERTY_CHARNUM);
      revealLineInEditor(t + 1, o + 1);
    };
    this.tree.init();
    if (!e.isToolWindow) {
      var n = createDOMElement(
        this.tree.sectionHeader,
        "div",
        "panelHeaderIcon ellipsesIcon"
      );
      n.onclick = (e) => {
        showContextMenu(undefined, e.clientX, e.clientY, [
          {
            id: "sortAlphabetically",
            name: "Sort Alphabetically",
            action: (e) => toggleOutlineShow(e),
            iconClass: toggleOutlineGetIconClass("sortAlphabetically"),
          },
          {},
          {
            id: "showClassFields",
            name: "Show Class Fields",
            action: (e) => toggleOutlineShow(e),
            iconClass: toggleOutlineGetIconClass("showClassFields"),
          },
          {
            id: "showModuleVariables",
            name: "Show Module Variables",
            action: (e) => toggleOutlineShow(e),
            iconClass: toggleOutlineGetIconClass("showModuleVariables"),
          },
          {
            id: "showEnumerations",
            name: "Show Enumerations",
            action: (e) => toggleOutlineShow(e),
            iconClass: toggleOutlineGetIconClass("showEnumerations"),
          },
          {
            id: "showUDTs",
            name: "Show User Defined Types",
            action: (e) => toggleOutlineShow(e),
            iconClass: toggleOutlineGetIconClass("showUDTs"),
          },
          {
            id: "showDLLs",
            name: "Show DLL Declares",
            action: (e) => toggleOutlineShow(e),
            iconClass: toggleOutlineGetIconClass("showDLLs"),
          },
          {
            id: "showConstructors",
            name: "Show Constructors",
            action: (e) => toggleOutlineShow(e),
            iconClass: toggleOutlineGetIconClass("showConstructors"),
          },
          {
            id: "showProperties",
            name: "Show Properties (Get/Let/Set)",
            action: (e) => toggleOutlineShow(e),
            iconClass: toggleOutlineGetIconClass("showProperties"),
          },
          {
            id: "showProcedures",
            name: "Show Procedures",
            action: (e) => toggleOutlineShow(e),
            iconClass: toggleOutlineGetIconClass("showProcedures"),
          },
          {
            id: "showVariables",
            name: "Show Variables",
            action: (e) => toggleOutlineShow(e),
            iconClass: toggleOutlineGetIconClass("showVariables"),
          },
          {
            id: "showParameters",
            name: "Show Parameters",
            action: (e) => toggleOutlineShow(e),
            iconClass: toggleOutlineGetIconClass("showParameters"),
          },
        ]);
        e.stopPropagation();
      };
    }
    this.tree.finishedInit();
  }
  rebuildFilteredTypes() {
    this.filteredTypes = {};
    if (!outlinePanelOptions["showClassFields"]) {
      this.filteredTypes["5_8"] = true;
    }
    if (!outlinePanelOptions["showModuleVariables"]) {
      this.filteredTypes["2_8"] = true;
    }
    if (!outlinePanelOptions["showEnumerations"]) {
      this.filteredTypes["5_10"] = true;
      this.filteredTypes["2_10"] = true;
    }
    if (!outlinePanelOptions["showUDTs"]) {
      this.filteredTypes["5_23"] = true;
      this.filteredTypes["2_23"] = true;
    }
    if (!outlinePanelOptions["showDLLs"]) {
      this.filteredTypes["5_524"] = true;
      this.filteredTypes["2_524"] = true;
    }
    if (!outlinePanelOptions["showConstructors"]) {
      this.filteredTypes["5_9"] = true;
    }
    if (!outlinePanelOptions["showProperties"]) {
      this.filteredTypes["5_7"] = true;
      this.filteredTypes["2_7"] = true;
    }
    if (!outlinePanelOptions["showProcedures"]) {
      this.filteredTypes["5_12"] = true;
      this.filteredTypes["2_12"] = true;
    }
    if (!outlinePanelOptions["showVariables"]) {
      this.filteredTypes["5_12_8"] = true;
      this.filteredTypes["5_7_8"] = true;
      this.filteredTypes["5_9_8"] = true;
      this.filteredTypes["2_12_8"] = true;
      this.filteredTypes["2_7_8"] = true;
    }
    if (!outlinePanelOptions["showParameters"]) {
      this.filteredTypes["5_524_520"] = true;
      this.filteredTypes["5_12_520"] = true;
      this.filteredTypes["5_7_520"] = true;
      this.filteredTypes["5_9_520"] = true;
      this.filteredTypes["2_524_520"] = true;
      this.filteredTypes["2_12_520"] = true;
      this.filteredTypes["2_7_520"] = true;
    }
  }
  syncSymbolsToFolder(e, t, o, n) {
    var i = e;
    if (this.sort) {
      i = e.slice();
      i.sort((e, t) => e.name.localeCompare(t.name));
    }
    if (this.filteredTypes === undefined) {
      this.rebuildFilteredTypes();
    }
    i.forEach((e) => {
      if (!this.filteredTypes[o + e.kind]) {
        if (e.children && e.children.length > 0) {
          var i = this.tree.view.data.addSubNode(
            t,
            e.name,
            e.detail,
            e.range.start.line,
            e.range.start.character,
            n
          );
          this.syncSymbolsToFolder(e.children, i, o + e.kind + "_", n + 1);
        } else {
          var r = this.tree.view.data.addSubNode(
            t,
            e.name,
            e.detail,
            e.range.start.line,
            e.range.start.character,
            n
          );
        }
      }
    });
  }
  syncSymbols(e) {
    this.tree.view.data.startMultiUpdate();
    this.tree.view.data.clear();
    this.sort = outlinePanelOptions["sortAlphabetically"] ? true : false;
    this.cachedSymbols = e;
    this.syncSymbolsToFolder(e, this.tree.view.data.rootFolder, "", 0);
    this.tree.view.data.endMultiUpdate();
  }
  resync() {
    this.syncSymbols(this.cachedSymbols);
  }
}
function toggleOutlineNode(e) {
  outlinePanel.tree.view.toggleExpanded(
    e.target.parentNode.parentNode.nodeVisibleIndex
  );
  e.stopPropagation();
}
function createOutlinePanel(e, t) {
  if (outlinePanel) return outlinePanel;
  outlinePanel = new _outlinePanel(e, t);
}
var packageManagerPanel = undefined;
var packageManagerPublisher = undefined;
var packageManagerNamespace = undefined;
var packageManagerDescription = undefined;
var packageManagerLicence = undefined;
var packageManagerVisibility = undefined;
var packageManagerVersion = undefined;
var packagePublisherName = "";
var packagePublisherPassword = "";
var packagePublisherSessionID = "";
var packagePublisherRememberPassword = false;
var packageManagerPublisherSingInLinkDomElement = undefined;
function ObfuscateString(e, t, o = 126) {
  var n = e.toString().split("");
  for (var i = 0; i < n.length; i++) {
    var r = n[i].charCodeAt(0);
    if (r <= o) {
      n[i] = String.fromCharCode((n[i].charCodeAt(0) + t) % o);
    }
  }
  return n.join("");
}
function UnobfuscateString(e, t, o = 126) {
  return ObfuscateString(e, o - t);
}
async function loadPublisherInfo() {
  await hostAppObject.GetIDESetting("PUBLISHER");
  var e = await hostAppObject.GetIDESetting("PUBLISHER");
  if (e) {
    var t = parseJson(e);
    if (t) {
      packagePublisherName = t.name ? t.name : "";
      packagePublisherPassword = t.pass ? UnobfuscateString(t.pass, 111) : "";
      if (packagePublisherPassword.length > 0)
        packagePublisherRememberPassword = true;
    }
  }
}
async function savePublisherInfo() {
  var e = { name: packagePublisherName };
  if (packagePublisherRememberPassword)
    e.pass = ObfuscateString(packagePublisherPassword, 111);
  await hostAppObject.SaveIDESetting("PUBLISHER", JSON.stringify(e));
}
function addCssClass(e) {
  document.getElementsByClassName("simpleMsgBoxNoImage")[0].classList.add(e);
}
function removeCssClass(e) {
  document.getElementsByClassName("simpleMsgBoxNoImage")[0].classList.remove(e);
}
function focusElement(e) {
  document.getElementById(e).focus();
}
function simulateClick(e) {
  document.getElementById(e).click();
}
function setPublisherError(e) {
  var t = document.getElementById("PublisherError");
  if (t) t.innerText = e.length > 0 ? "ERROR: " + e : "";
}
function serverHttpsGetUtf8(e, t, o, n, i) {
  e = e.replaceAll("#", "%23");
  var r = new XMLHttpRequest();
  r.onreadystatechange = () => {
    if (r.readyState == 4 && r.status == 200) {
      if (t) t(r.responseText);
    } else if (r.readyState == 4 && r.status != 0) {
      if (o) o(r.status);
    }
  };
  r.onerror = () => {
    if (o) o(r.status);
  };
  r.overrideMimeType("text/plain; charset=UTF-8");
  r.open(n ? "POST" : "GET", "https://www.everythingaccess.com" + e, true);
  if (i) {
    i.forEach((e) => {
      r.setRequestHeader(e.name, e.value);
    });
  }
  r.send(n ? n : null);
}
function getInputValue(e) {
  var t = document.getElementById(e);
  if (t.type === "checkbox") {
    return t.checked;
  }
  return t.value;
}
function packagePublisherPublishNow(e, t, o) {
  debugOutputLine(
    "[PUBLISH] attempting to publish project '" +
      t +
      "' to the online database..."
  );
  serverHttpsGetUtf8(
    "/twinbasic/packages/publish?auth=" + packagePublisherSessionID,
    () => {
      showModalNotification(
        "[PUBLISH] successful.  Your package should appear in the package manager database shortly."
      );
    },
    (e) => {
      debugger;
      if (!o && e == 552) {
        packageManagerPanel.showSignInForm();
      } else if (e == 551) {
        showModalNotification(
          "[PUBLISH] FAILED.  Package already uploaded with this exact version number."
        );
      } else if (e == 553) {
        showModalNotification(
          "[PUBLISH] FAILED.  Package already registered to another publisher (change your Project ID setting)."
        );
      } else if (e !== 200) {
        showModalNotification(
          "[PUBLISH] FAILED.  Server returned HTTPS code " + e,
          true
        );
      }
    },
    e,
    [
      { name: "Content-Type", value: "application/octet-stream" },
      { name: "Content-Length", value: e.length },
    ]
  );
}
function packagePublisherPublish() {
  if (packagePublisherSessionID.length == 0) {
    packageManagerPanel.showSignInForm();
    return;
  }
  debugSocket.request("generateTWINPACK", undefined, (e) => {
    var t = e.body;
    if (t.projectId == "{00000000-0000-0000-0000-000000000000}") {
      showModalNotification(
        `ERROR: Please first edit the Settings, giving the project a proper name and description`
      );
    } else {
      var o =
        root.RootProjectPackageVisibility === "PUBLIC"
          ? "WARNING: publishing a PUBLIC package will allow everyone to download the package and see the sourcecode within it.\r\n\r\n"
          : "";
      var n = `${o}IMPORTANT: Please check the following information before publishing to the online database:\r\n\r\nPUBLISHER: ${packagePublisherName}\r\n\r\nPACKAGE NAMESPACE: ${t.projectName}\r\nPACKAGE DESCRIPTION: ${t.projectDescription}\r\nPACKAGE VERSION: ${t.versionMajor}.${t.versionMinor}.${t.versionBuild}.${t.versionRevision}\r\n\r\nPACKAGE LICENCE: ${t.licence}\r\n\r\nDo you want to proceed?`;
      var i = createDOMElement(undefined, "div", "simpleMsgBox", n);
      showModalDialog(i, [
        {
          caption: "PROCEED",
          onclick: () => {
            hideModalDialog();
            base64ToBufferAsync(t.fileBase64, (e) => {
              packagePublisherPublishNow(e, t.projectName);
            });
          },
          isDefaultCancelAction: false,
        },
        {
          caption: "取消",
          onclick: () => {
            hideModalDialog();
          },
          isDefaultCancelAction: true,
        },
      ]);
    }
  });
}
function packagePublisherRegister(e, t, o, n, i) {
  setPublisherError("");
  if (!e || e.length < 4) {
    setPublisherError("Username must be at least 4 characters long");
    focusElement("PublisherUserId");
    return;
  }
  const r = (e) =>
    String(e)
      .toLowerCase()
      .match(
        /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|.(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
      );
  if (!t || !r(t)) {
    setPublisherError("invalid email address");
    focusElement("PublisherEmail");
    return;
  }
  if (!o || o.length < 8) {
    setPublisherError("Password must be at least 8 characters long");
    focusElement("PublisherPassword");
    return;
  }
  if (n != true) {
    setPublisherError("You must agree to the terms and conditions");
    return;
  }
  packagePublisherRememberPassword = i == true;
  serverHttpsGetUtf8(
    "/twinbasic/packages/publisherCreate?id=" +
      e +
      "&email=" +
      t +
      "&password=" +
      o,
    (t) => {
      packagePublisherName = e;
      if (packagePublisherRememberPassword) packagePublisherPassword = o;
      packageManagerPanel.signOut();
      hideModalDialog();
      showModalNotification(
        "Publisher account created successfully.  You will now be logged in.",
        () => {
          savePublisherInfo();
          packagePublisherLogin(e, o, packagePublisherRememberPassword);
        }
      );
    },
    (e) => {
      if (e == 553) {
        setPublisherError("Username already taken.");
      } else if (e !== 0) {
        setPublisherError(
          "Publisher registration FAILED.  Server returned HTTPS code " + e
        );
      } else {
        setPublisherError(
          "Publisher registration FAILED.   HTTPS request to server (www.everythingaccess.com) failed.  Try again later."
        );
      }
    }
  );
}
function packagePublisherLogin(e, t, o) {
  packagePublisherName = e;
  packagePublisherPassword = t ? t : "";
  packageManagerPanel.packagePublisherLogin(() => {
    packagePublisherRememberPassword = o == true;
    packageManagerPublisher.innerText = packagePublisherName;
    savePublisherInfo();
    if (!o) packagePublisherPassword = "";
  });
}
function showPublisherSignInForm() {
  packageManagerPanel.showSignInForm();
}
function setPublisherSessionId(e) {
  packagePublisherSessionID = e ? e : "";
}
class _packageManagerPanel {
  show() {
    this._this.sectionRoot.classList.remove("sectionRootHidden");
    this._this.sectionHeader.classList.remove("sectionHeaderHidden");
  }
  hide() {
    this._this.sectionRoot.classList.add("sectionRootHidden");
    this._this.sectionHeader.classList.add("sectionHeaderHidden");
  }
  signOut() {
    packageManagerPublisher.innerText = "";
    packageManagerPublisherSingInLinkDomElement.innerText = "SIGN IN";
    setPublisherSessionId("");
  }
  packagePublisherLogin(e) {
    setPublisherError("");
    if (packagePublisherPassword.length == 0) {
      this.showSignInForm();
      return;
    }
    serverHttpsGetUtf8(
      "/twinbasic/packages/publisherLogin?id=" +
        packagePublisherName +
        "&password=" +
        packagePublisherPassword,
      (t) => {
        setPublisherSessionId(t);
        packageManagerPublisherSingInLinkDomElement.innerText = "SIGN OUT";
        hideModalDialog();
        if (e) e();
      },
      (e) => {
        if (e === 553) {
          setPublisherError(
            "Publisher login FAILED.  Username not found.",
            showPublisherSignInForm
          );
        } else if (e === 555) {
          setPublisherError(
            "Publisher login FAILED.  Incorrect password.",
            showPublisherSignInForm
          );
        } else if (e !== 0) {
          setPublisherError(
            "Publisher login FAILED.  Server returned HTTPS code " + e,
            showPublisherSignInForm
          );
        } else {
          setPublisherError(
            "Publisher login FAILED.  HTTPS request to server (www.everythingaccess.com) failed.  Try again later.",
            showPublisherSignInForm
          );
        }
      }
    );
  }
  showSignInForm(e) {
    var t = `\n                        <div id='PublisherSignUp'>\n                            <div id='LoginOptions'>\n                                <div id='LoginButton' onclick='addCssClass("isLogin"); focusElement("PublisherUserIdLogin");'>LOGIN</div>\n                                <div id='SignupButton' onclick='removeCssClass("isLogin"); focusElement("PublisherUserId");'>REGISTER</div>\n                            </div>\n\n                            <div id='PublisherLoginGroup'>\n                                <br/><div id='PublisherLogInUserIdLabel'>USERNAME</div><input id='PublisherUserIdLogin' type='text' value='${packagePublisherName}' onkeyup='if(event.keyCode == 13) focusElement("PublisherPasswordLogin"); return true;'/>\n                                <br/><div id='PublisherLogInPasswordLabel'>PASSWORD</div><input id='PublisherPasswordLogin' type='password' value='${packagePublisherPassword}' onkeyup='if(event.keyCode == 13) simulateClick("PublisherLogInButton"); return true;'/>\n                                <br/>\n                                <br/><div id='PublisherLoginRememberPasswordContainer'><input id='PublisherLoginRememberPassword' type='checkbox'/>Remember password on this device</div>    \n                                <br/><div id='PublisherLogInButton' onclick='packagePublisherLogin(getInputValue("PublisherUserIdLogin"), getInputValue("PublisherPasswordLogin"), getInputValue("PublisherLoginRememberPassword"));'>LOG IN &nbsp; &#10148;</div>    \n                            </div> \n                            <div id='PublisherSignupGroup'>\n                                <br/><div id='PublisherSignUpUserIdLabel'>USERNAME</div><div class='group'><input id='PublisherUserId' type='text' onkeydown='if(event.keyCode == 13) simulateClick("PublisherSignUpButton"); return true;'/><div class='keepTogether'>&gt;=4 characters, visible to everyone, no expletives</div></div>\n                                <br/><div id='PublisherSignUpEmailLabel'>EMAIL</div><div class='group'><input id='PublisherEmail' type='text' onkeydown='if(event.keyCode == 13) simulateClick("PublisherSignUpButton"); return true;'/><div class='keepTogether'>this is used for account recovery only</div></div>\n                                <br/><div id='PublisherSignUpPasswordLabel'>PASSWORD</div><div class='group'><input id='PublisherPassword' type='password' onkeydown='if(event.keyCode == 13) simulateClick("PublisherSignUpButton"); return true;'/><div class='keepTogether'>&gt;=8 characters</div></div>\n                                <br/><div id='PublisherAgreeTermsContainer'><input id='PublisherAgreeTerms' type='checkbox'/>I agree to the terms &amp; conditions</div>    \n                                <br/><div id='PublisherRememberPasswordContainer'><input id='PublisherRememberPassword' type='checkbox'/>Remember password on this device</div>    \n                                <br/><div id='PublisherSignUpButton' onclick='packagePublisherRegister(getInputValue("PublisherUserId"), getInputValue("PublisherEmail"), getInputValue("PublisherPassword"), getInputValue("PublisherAgreeTerms"), getInputValue("PublisherRememberPassword"));'>SIGN UP &nbsp; &#10148;</div>   \n                            </div> \n                            <div id='PublisherError'></div>    \n                        </div>\n\n                        <div id='terms'>\n                        <h2 style='margin-top: 0;'>TERMS AND CONDITIONS</h2>\n                        This service is subject to the following Terms and Conditions. &nbsp;These terms may be updated at any time without notice to you.\n                        <br/>\n                        <br/>This service allows you to store and share your content and/or receive material from others. &nbsp;We don't claim ownership of your content; it remains your content and you are responsible for it.\n                        <br/>\n                        <br/>Use of this service is at your own risk. &nbsp;Published packages may contain full source code which will be visible to everyone using this service.\n                        <ul>\n                            <li>Don't do anything illegal.</li>\n                            <li>Don't publish spam.</li>\n                            <li>Don't engage in any activity that exploits or harms children.</li>\n                            <li>Don't use the service to share inappropriate content (e.g., nudity, pornography, violence, or criminal activity).</li>\n                            <li>Don't attempt to circumvent security/authentication restrictions.</li>\n                            <li>Don't attempt to damage, overburden, or impair the services.</li>\n                            <li>Don't engage in any activity that is false or misleading (e.g., impersonating someone).</li>\n                            <li>Don't engage in any activity that is harmful to you, the service, or others (e.g., publishing viruses).</li>\n                            <li>Don't infringe upon the rights of others (e.g., unauthorized sharing of copyrighted material).</li>\n                            <li>Don't help others break these rules.</li>\n                        </ul>\n                        <br/>If you violate these terms, we may stop providing the service to you, close your account, revoke your access, or delete or unlist your package(s).\n                        <br/>\n                        <br/>In using the service, you agree to comply with all applicable Export Laws.\n                        <br/>\n                        <br/>If you have any basis for recovering damages, you agree that your exclusive remedy is to recover, from Wayne Phillips T/A iTech Masters or any affiliates, distributors, and vendors, direct aggregate damages up to £1.00. &nbsp;You can't recover any other damages or losses, including consequential, lost profits, special, indirect, incidental, or punitive. &nbsp;These limitations and exclusions apply even if this remedy doesn't fully compensate you for any losses or fails of its essential purpose or if we knew or should have known about the possibility of the damages. &nbsp;To the maximum extent permitted by law, these limitations and exclusions apply to all claims against the services provided, and the software related to the services.\n                        <br/>\n                        </div>\n                    `;
    var o = createDOMElement(undefined, "div", "simpleMsgBoxNoImage");
    o.innerHTML = t;
    showModalDialog(
      o,
      [
        {
          caption: "取消",
          onclick: hideModalDialog,
          isDefaultCancelAction: true,
        },
      ],
      "twinBASIC Publisher Login / Signup"
    );
    if (packagePublisherName.length > 0) {
      addCssClass("isLogin");
      focusElement("PublisherPasswordLogin");
    } else {
      focusElement("PublisherUserId");
    }
    var n = document.getElementById("PublisherLoginRememberPassword");
    n.checked = packagePublisherRememberPassword;
  }
  constructor(e, t) {
    this.id = 0;
    var o = {};
    o.sectionExpander = createDOMElement(
      undefined,
      "div",
      "panelHeaderIconLeft sectionExpanderIcon"
    );
    o.panelDiv = e;
    o.sectionHeaderInner = createDOMElement(
      undefined,
      "div",
      "sectionHeaderInner",
      "打包发布"
    );
    o.sectionRoot = createDOMElement(undefined, "div", "sectionRoot");
    o.sectionBody = createDOMElement(o.sectionRoot, "div", "sectionBody");
    var n = createDOMElement(o.sectionBody, "div", "packageManagerOuter");
    var i = createDOMElement(n, "div", "packageManagerInner");
    var r = createDOMElement(n, "div", "packageManagerInner2");
    {
      let e = createDOMElement(i, "div", "packageManagerRow");
      createDOMElement(e, "div", "packageManagerHeader", "Publisher");
      packageManagerPublisher = createDOMElement(
        e,
        "div",
        "packageManagerData"
      );
      let t = createDOMElement(e, "div", "packageManagerLink", "SIGN IN");
      t.onclick = () => {
        if (packagePublisherSessionID.length > 0) {
          this.signOut();
        } else {
          this.showSignInForm();
        }
      };
      packageManagerPublisherSingInLinkDomElement = t;
    }
    {
      let e = createDOMElement(i, "div", "packageManagerRow");
      createDOMElement(e, "div", "packageManagerHeader", "Namespace");
      packageManagerNamespace = createDOMElement(
        e,
        "div",
        "packageManagerData"
      );
      let t = createDOMElement(e, "div", "packageManagerLink", "EDIT");
      t.onclick = () => {
        showIndividualSetting("project.name");
      };
    }
    {
      let e = createDOMElement(i, "div", "packageManagerRow");
      createDOMElement(e, "div", "packageManagerHeader", "Description");
      packageManagerDescription = createDOMElement(
        e,
        "div",
        "packageManagerData"
      );
      let t = createDOMElement(e, "div", "packageManagerLink", "EDIT");
      t.onclick = () => {
        showIndividualSetting("project.description");
      };
    }
    {
      let e = createDOMElement(i, "div", "packageManagerRow");
      createDOMElement(e, "div", "packageManagerHeader", "Licence");
      packageManagerLicence = createDOMElement(e, "div", "packageManagerData");
      let t = createDOMElement(e, "div", "packageManagerLink", "EDIT");
      t.onclick = () => {
        showIndividualSetting("project.licence");
      };
    }
    {
      let e = createDOMElement(i, "div", "packageManagerRow");
      createDOMElement(e, "div", "packageManagerHeader", "Visibility");
      packageManagerVisibility = createDOMElement(
        e,
        "div",
        "packageManagerData"
      );
      let t = createDOMElement(e, "div", "packageManagerLink", "EDIT");
      t.onclick = () => {
        showIndividualSetting("project.packageVisibility");
      };
    }
    {
      let e = createDOMElement(i, "div", "packageManagerRow");
      createDOMElement(e, "div", "packageManagerHeader", "Version");
      packageManagerVersion = createDOMElement(e, "div", "packageManagerData");
      let t = createDOMElement(e, "div", "packageManagerLink", "EDIT");
      t.onclick = () => {
        showIndividualSetting("project.version");
      };
    }
    {
      let e = createDOMElement(r, "div", "packageManagerFullLine");
      e.innerText = "(changes not effective until published)";
    }
    {
      let e = createDOMElement(r, "div", "packageManagerPublish");
      e.innerText = "PUBLISH THIS PACKAGE";
      e.onclick = () => {
        packagePublisherPublish();
      };
    }
    i.spellcheck = false;
    i.autocomplete = false;
    o.friendlyName = "打包发布";
    assignToPanel(o, undefined, o.panelDiv);
    o.sectionHeader.sectionRoot = o.sectionRoot;
    if (o.sectionHeader.restoreCustomSize) o.sectionHeader.restoreCustomSize();
    o.sectionHeader.panelId = "打包发布";
    this._this = o;
    this.hide();
  }
}
function syncPackageManagerPanel() {
  packageManagerNamespace.innerText = g_CurrentProjectName;
  packageManagerDescription.innerText = g_CurrentProjectDescription;
  packageManagerLicence.innerText = g_CurrentProjectLicence;
  packageManagerVisibility.innerText = g_CurrentProjectVisibility;
  packageManagerVersion.innerText =
    g_CurrentProjectMajorVersion +
    "." +
    g_CurrentProjectMinorVersion +
    "." +
    g_CurrentProjectBuildVersion +
    "." +
    g_CurrentProjectRevisionVersion;
  if (g_CurrentProjectIsPackage) {
    packageManagerPanel.show();
  } else {
    packageManagerPanel.hide();
  }
}
function createPackageManagerPanel(e, t) {
  if (packageManagerPanel) return packageManagerPanel;
  packageManagerPanel = new _packageManagerPanel(e, t);
}
var openEditors;
var codePanelTabs;
var previewingEditorNode;
var tabsHistory = [];
function removeItemAll(e, t) {
  var o = 0;
  while (o < e.length) {
    if (e[o] === t) {
      e.splice(o, 1);
    } else {
      ++o;
    }
  }
  return e;
}
function initOpenEditorsPanel() {
  codePanelTabs = document.getElementById("codePanelTabs");
}
function onDragTabStart(e, t, o) {
  startDropZone = t;
  startDropZoneItem = o;
  currentDragType = DRAG_TAB;
  hideTooltipNow();
  e.dataTransfer.setData("text/plain", o.name);
}
function onDragTabDropped(e) {
  if (currentDragType !== DRAG_TAB) return;
  e.preventDefault();
  if (currentDropZone != startDropZone) {
    var t = e.dataTransfer.getData("text/plain");
    if (currentDropZone.classList.contains("tabDropZoneLeft")) {
      startDropZone.parentElement.insertBefore(startDropZone, currentDropZone);
    } else {
      if (currentDropZone.nextSibling) {
        startDropZone.parentElement.insertBefore(
          startDropZone,
          currentDropZone.nextSibling
        );
      } else {
        startDropZone.parentElement.appendChild(startDropZone);
      }
    }
  }
}
function onDragTabHover(e, t, o) {
  if (currentDragType !== DRAG_TAB) return;
  e.preventDefault();
  if (o.tree !== startDropZoneItem.tree) {
    e.dataTransfer.dropEffect = "none";
    return;
  }
  e.dataTransfer.dropEffect = "move";
  var n = "tabDropZoneLeft";
  if (t != startDropZone) {
    var i = t.getBoundingClientRect();
    if (e.clientX > i.left + i.width / 2) {
      n = "tabDropZoneRight";
    }
  }
  {
    if (currentDropZone) {
      currentDropZone.classList.remove("tabDropZoneLeft");
      currentDropZone.classList.remove("tabDropZoneRight");
      currentDropZone = undefined;
    }
    if (t && t != startDropZone) {
      t.classList.add(n);
    }
    currentDropZone = t;
    currentDropZoneItem = o;
  }
}
function onDragTabEnd(e, t, o) {
  currentDragType = undefined;
  if (currentDropZone) {
    currentDropZone.classList.remove("tabDropZoneLeft");
    currentDropZone.classList.remove("tabDropZoneRight");
    currentDropZone = undefined;
  }
  o.tree.unhideHoverElement();
}
class openEditorsCollection {
  constructor(e, t, o, n, i, r) {
    this.editorContentId = 0;
    this.tree = new treeView(e, "打开", "editors:", false, 5, true);
    this.tree.render();
    this.selectedEditorNode = undefined;
    this.tree.onClickItem = (e, t) => {
      this.changeSelectedEditor(t);
    };
  }
  getEditorsAssociatedWithFolder(e, t) {
    var o = [];
    this.tree.rootFolder.enumerateContent(true, (n) => {
      var i = n.fileNode.getFullPath();
      if (i.indexOf(e + "/") == 0) {
        if (!t || this.isDirtyEditor(n)) {
          o.push(n.fileNode);
        }
      }
      return true;
    });
    return o;
  }
  closeAllEditorsInFolder(e) {
    this.tree.rootFolder.enumerateContent(true, (t) => {
      if (t.fileNode.getFullPath().indexOf(e + "/") == 0) {
        this.closeFileNow(t, false);
      }
      return true;
    });
  }
  closeAllTabsNoSave() {
    for (let t = 0; t < codePanelTabs.childNodes.length; t++) {
      try {
        var e = codePanelTabs.childNodes[t].editorNode;
        this.closeFileNow(e, false);
      } catch (e) {}
    }
  }
  closeEditor(e) {
    this.tree.rootFolder.enumerateContent(true, (t) => {
      if (t.fileNode.getFullPath() === e) {
        this.closeFileNow(t, false);
      }
      return true;
    });
  }
  closeAllExcept(e, t, o) {
    this.tree.rootFolder.enumerateContent(true, (n) => {
      if (n !== e) {
        if (!t || this.isDirtyEditor(n) === false) {
          if (o) {
            this.closeFileNow(n);
          } else {
            this.closeFile(n);
          }
        }
      }
      return true;
    });
  }
  saveAll() {
    this.tree.rootFolder.enumerateContent(true, (e) => {
      if (this.isDirtyEditor(e)) {
        e.fileHandler.save(e);
      }
      return true;
    });
  }
  save(e) {
    if (this.isDirtyEditor(e)) {
      e.fileHandler.save(e);
    }
  }
  hasDirtyEditors() {
    var e = 0;
    this.tree.rootFolder.enumerateContent(true, (t) => {
      if (this.isDirtyEditor(t)) {
        e++;
      }
      return true;
    });
    return e;
  }
  getCount() {
    return Object.keys(this.tree.rootFolder.entries).length;
  }
  getCountUnsaved() {
    var e = 0;
    this.tree.rootFolder.enumerateContent(true, (t) => {
      if (openEditors.isDirtyEditor(t)) {
        e++;
      }
      return true;
    });
    return e;
  }
  closeFileNow(e, t, o) {
    e.fileHandler.closing(e, t, () => {
      e.tabElement.parentElement.removeChild(e.tabElement);
      if (e.parentFolder) e.parentFolder.removeItem(e);
      delete e.tabElement;
      delete e.fileNode.openEditorNode;
      removeItemAll(tabsHistory, e);
      if (e === this.selectedEditorNode) {
        outlinePanel.syncSymbols([]);
        e.fileHandler.deactivated(e);
        this.selectedEditorNode = undefined;
        if (tabsHistory.length) {
          if (!o)
            openEditors.changeSelectedEditor(
              tabsHistory[tabsHistory.length - 1]
            );
        } else {
          var t = this.tree.rootFolder.getFirstItem();
          if (!o) openEditors.changeSelectedEditor(t);
        }
        if (!o) {
          if (Object.keys(this.tree.rootFolder.entries).length === 0) {
            openEditors.editorContentId++;
            root.notifyChangedActiveEditor(0, "", "", -1);
          }
        }
      }
      if (e.fileHandler.closed) e.fileHandler.closed(e);
      if (e == previewingEditorNode) {
        previewingEditorNode = undefined;
      }
      unsetTooltip();
      changedSize();
    });
  }
  closeFile(e) {
    if (this.isDirtyEditor(e)) {
      var t = createDOMElement(
        undefined,
        "div",
        "simpleMsgBox",
        `您是否要保存更改： ${e.name}?`
      );
      createDOMElement(
        t,
        "div",
        "subtext",
        `如果您不保存，您的更改将丢失。`
      );
      showModalDialog(t, [
        {
          caption: "保存",
          onclick: () => {
            this.closeFileNow(e, true);
            hideModalDialog();
          },
        },
        {
          caption: "放弃更改",
          onclick: () => {
            this.closeFileNow(e, false);
            hideModalDialog();
          },
        },
        {
          caption: "取消",
          onclick: () => {
            hideModalDialog();
          },
          isDefaultCancelAction: true,
        },
      ]);
    } else {
      this.closeFileNow(e, false);
    }
  }
  changeSelectedEditor(e, t, o, n) {
    if (this.selectedEditorNode != e) {
      if (this.selectedEditorNode) {
        this.selectedEditorNode.fileHandler.deactivated(
          this.selectedEditorNode
        );
        this.selectedEditorNode.tabElement.classList.remove("tabItemSelected");
        this.selectedEditorNode = undefined;
      }
      openEditors.editorContentId++;
      let i = openEditors.editorContentId;
      e.tabElement.classList.add("tabItemSelected");
      this.selectedEditorNode = e;
      e.fileHandler.activated(e, t, o, n);
      tabsHistory.push(e);
      root.notifyChangedActiveEditor(
        0,
        e.type,
        e.fileNode.getFullPath ? "twinbasic:" + e.fileNode.getFullPath() : "",
        i
      );
    } else {
      if (t) {
        if (!liveIDEOptions["previewDocs"]) {
          this.selectedEditorNode.fileNode.tree.changeSelection(
            this.selectedEditorNode.fileNode,
            o,
            n
          );
        }
      }
    }
    if (!e) {
      statusLineCol.classList.add("hide");
      codePanelMainInnerMonacoContainer.classList.add("hide");
      codePanelDropDownContainer.classList.add("hideNotCodeEditor");
      changedSize();
      codePanelMain.style.visibility = "hidden";
      return;
    } else {
      codePanelMain.style.visibility = "visible";
    }
  }
  createTabElement(e, t) {
    var o = createDOMElement(codePanelTabs, "div", "tabItem");
    o.editorNode = e;
    var n = e.name;
    if (n && n.length > 0) {
      var i = n.indexOf("␞");
      if (i != -1) {
        n = n.substring(0, i);
      }
    }
    createDOMElement(o, "div", "tabItemIconLeft " + e.iconClass);
    e.domObject_TextPart = createDOMElement(
      o,
      "div",
      "tabItemText " + (t ? " tabItemPreview" : ""),
      n
    );
    e.domObject_CloseButton = createDOMElement(o, "div", "progressSpinnerIcon");
    e.domObject_CloseButton.onclick = (t) => {
      this.closeFile(e);
      t.stopPropagation();
    };
    o.onclick = () => {
      this.changeSelectedEditor(e);
    };
    o.oncontextmenu = (t) => {
      showContextMenu(undefined, t.clientX, t.clientY, [
        {
          name: "Close",
          action: () => {
            this.closeFile(e);
          },
        },
        {
          name: "Close Others",
          action: () => {
            openEditors.closeAllExcept(e);
          },
        },
        {
          name: "Close Saved",
          action: () => {
            openEditors.closeAllExcept(undefined, true);
          },
        },
        {
          name: "Close All",
          action: () => {
            openEditors.closeAllExcept(undefined);
          },
        },
      ]);
      return false;
    };
    o.onmouseenter = (t) => {
      setTooltip(e.fileNode.toolTip, t.clientX + 10, t.clientY + 10);
    };
    o.onmousemove = (e) => {
      setTooltipPosition(e.clientX + 10, e.clientY + 10);
    };
    o.onmouseleave = (e) => {
      unsetTooltip(true);
    };
    o.draggable = true;
    o.ondragstart = (t) => {
      onDragTabStart(t, o, e);
    };
    o.ondragover = (t) => {
      onDragTabHover(t, o, e);
    };
    o.ondragend = (t) => {
      onDragTabEnd(t, o, e);
    };
    o.ondrop = (e) => {
      onDragTabDropped(e);
    };
    return o;
  }
  isDirtyEditor(e) {
    return e.fileHandler.isDirty(e);
  }
  updateDirtyState(e) {
    if (this.isDirtyEditor(e)) {
      if (!e.cachedIsDirtyState) {
        e.cachedIsDirtyState = true;
        e.domObject_CloseButton.classList.add("circleIconSmall");
        this.convertPreviewTabToRealTab(e);
      }
    } else {
      if (e.cachedIsDirtyState) {
        e.cachedIsDirtyState = false;
        e.domObject_CloseButton.classList.remove("circleIconSmall");
      }
    }
  }
  convertPreviewTabToRealTab(e) {
    e.domObject_TextPart.classList.remove("tabItemPreview");
    if (previewingEditorNode === e) previewingEditorNode = undefined;
  }
  resyncToFileSystem() {
    for (let n = 0; n < codePanelTabs.childNodes.length; n++) {
      try {
        var e = codePanelTabs.childNodes[n].editorNode;
        if (e) {
          debugger;
          var t = e.fileNode;
          while (t.parentFolder) {
            if (t.parentFolder.isRootFolder) break;
            t = t.parentFolder;
          }
          var o =
            fs.tree.rootFolder.entries[
              Object.keys(fs.tree.rootFolder.entries)[0]
            ];
          t.name = o.name;
          e.fileHandler.resyncToFileSystem(e);
        }
      } catch (e) {}
    }
  }
  getOpenEditors() {
    var e = [];
    for (let i = 0; i < codePanelTabs.childNodes.length; i++) {
      var t = codePanelTabs.childNodes[i].editorNode;
      if (t) {
        var o = t === openEditors.selectedEditorNode;
        var n = o
          ? t.monacoModelInstance
            ? editor.saveViewState()
            : undefined
          : t.monacoViewState;
        try {
          let i = t.fileNode.getFullPath();
          e.push({ uri: i, state: n, isSelected: o });
        } catch (e) {}
      }
    }
    return e;
  }
  syncEditorToFileSystem(e, t) {
    {
      fs.readFile(e, (o, n) => {
        if (o >= 0) {
          e.openEditorNode.isSystemANSIFile = o === 1;
          e.openEditorNode.fileHandler.gotFileData(e.openEditorNode, n);
          e.openEditorNode.domObject_CloseButton.className = "tabItemIconRight";
          if (t) t();
        }
      });
    }
  }
  openFile(e, t, o, n, i, r, s, a, l) {
    if (previewingEditorNode) {
      if (e.openEditorNode === previewingEditorNode) {
        this.changeSelectedEditor(e.openEditorNode, t, o, n);
        if (t) {
          if (i)
            e.openEditorNode.fileHandler.onReveal(e.openEditorNode, i, r, s);
          if (a) a();
          return;
        }
        this.convertPreviewTabToRealTab(e.openEditorNode);
        e.openEditorNode.fileHandler.onFocus(e.openEditorNode);
        if (i) e.openEditorNode.fileHandler.onReveal(e.openEditorNode, i, r, s);
        if (a) a();
        return e.openEditorNode;
      }
      this.closeFileNow(previewingEditorNode, false, true);
    }
    if (!e.openEditorNode) {
      if (t) {
        if (!liveIDEOptions["previewDocs"]) {
          e.tree.changeSelection(e, o, n);
          return;
        }
      }
      doLayoutChanges(() => {
        e.openEditorNode = this.tree.rootFolder.addItem(
          e.name,
          e.iconClass,
          e.treeItemClass,
          e.toolTip
        );
        var a = e.openEditorNode;
        e.openEditorNode.monacoViewState = l;
        e.openEditorNode.pendingLineEdits = [];
        e.openEditorNode.fileNode = e;
        e.openEditorNode.tabElement = this.createTabElement(
          e.openEditorNode,
          t
        );
        e.openEditorNode.initialOptions = {
          preview: t,
          ctrlKey: o,
          shiftKey: n,
          line: i,
          column: r,
          viewPortTop: s,
        };
        var d = "";
        if (e.name.indexOf(".") != -1)
          d = e.name.split(".").pop().toLowerCase();
        e.openEditorNode.fileExtension = d;
        if (d === "twin" || d === "bas" || d === "cls") {
          e.openEditorNode.fileHandler = fileHandler_twin;
        } else if (d === "tbform" || d === "tbcontrol" || d === "tbppage") {
          e.openEditorNode.fileHandler = fileHandler_tbform;
        } else if (
          d === "ico" ||
          d === "cur" ||
          d === "png" ||
          d === "gif" ||
          d === "jpg" ||
          d === "jpeg" ||
          d === "svg" ||
          d === "pdf" ||
          d === "bmp"
        ) {
          e.openEditorNode.fileHandler = fileHandler_preview;
        } else if (e.name === "项目设置") {
          e.openEditorNode.fileHandler = fileHandler_config;
        } else if (
          d === e.name.toLowerCase() &&
          e.parentFolder.name == "References"
        ) {
          e.openEditorNode.fileHandler = fileHandler_twin;
        } else if (d === "") {
          var c = e.getFullPath();
          if (c.indexOf("/Resources/CURSOR/") != -1) {
            e.openEditorNode.fileHandler = fileHandler_preview;
            e.openEditorNode.fileExtension = "cur";
          } else if (c.indexOf("/Resources/ICON/") != -1) {
            e.openEditorNode.fileHandler = fileHandler_preview;
            e.openEditorNode.fileExtension = "ico";
          } else if (c.indexOf("/Resources/BITMAP/") != -1) {
            e.openEditorNode.fileHandler = fileHandler_preview;
            e.openEditorNode.fileExtension = "bmp";
          } else if (c.indexOf("/References/") != -1) {
            e.openEditorNode.fileHandler = fileHandler_twin;
          } else {
            e.openEditorNode.fileHandler = fileHandler_text;
          }
        } else {
          e.openEditorNode.fileHandler = fileHandler_text;
        }
        if (t) previewingEditorNode = e.openEditorNode;
      });
      changedSize();
      this.syncEditorToFileSystem(e, a);
    } else {
      this.changeSelectedEditor(e.openEditorNode, t, o, n);
      if (i) e.openEditorNode.fileHandler.onReveal(e.openEditorNode, i, r, s);
      if (a) a();
    }
    return e.openEditorNode;
  }
}
function createOpenEditors(e) {
  if (openEditors) return openEditors;
  openEditors = new openEditorsCollection(e);
}
var leftPanel;
var rightPanel;
var centerInnerPanel;
var isRestoringPanelConfigurations = false;
var isRestoringPanelConfigurations2 = false;
var floatingToolWindowsData = {};
var panelLayout = {};
async function initLayout(e) {
  try {
    panelLayout = JSON.parse(await hostAppObject.GetIDESetting("LAYOUT"));
  } catch (e) {}
  if (!panelLayout) panelLayout = {};
  if (typeof panelLayout !== "object") panelLayout = {};
  floatingToolWindowsData = panelLayout.floatingToolWindows;
  if (typeof floatingToolWindowsData !== "object") floatingToolWindowsData = {};
  e();
}
function assignToPanel(e, t, o, n) {
  if (t) {
    e = t._this;
    if (!t.parentNode.isVerticalPanel) {
      t.parentNode.parentNode.removeChild(t.parentNode);
    }
    t.parentNode.removeChild(t);
    e.panelDiv.layoutChanged(e.panelDiv);
  }
  e.panelDiv = o;
  e.sectionHeader = e.panelDiv.addPanelSection(
    e.friendlyName,
    e.panelDiv,
    "sectionHeader",
    false,
    n
  );
  e.sectionHeader._this = e;
  e.sectionHeader.sectionRoot = e.sectionRoot;
  if (e.sectionHeader.restoreCustomSize) e.sectionHeader.restoreCustomSize();
  e.sectionRoot.tabIndex = "0";
  e.sectionRoot.ondragover = (t) => {
    onDragPanelSectionHover(t, e.sectionHeader);
  };
  e.sectionRoot.ondrop = (e) => {
    onDragPanelSectionDropped(e);
  };
  e.sectionHeader.sectionRoot = e.sectionRoot;
  if (!isRestoringPanelConfigurations) {
    e.sectionHeader.sectionRoot.style = "";
  }
  if (e.sectionExpander) {
    e.sectionHeader.appendChild(e.sectionExpander);
    if (e.panelDiv.isVerticalPanel && !e.panelDiv.isToolWindow) {
      e.sectionExpander.classList.remove("hide");
    } else {
      e.sectionExpander.classList.add("hide");
      e.sectionRoot.classList.remove("sectionHidden");
      e.sectionHeader.classList.remove("sectionHeaderCollapsed");
    }
  }
  e.sectionHeader.appendChild(e.sectionHeaderInner);
  if (n && e.panelDiv.isVerticalPanel) {
    if (e.filterTextOuter)
      e.sectionHeader.parentNode.insertBefore(e.filterTextOuter, n);
    e.sectionHeader.parentNode.insertBefore(e.sectionRoot, n);
  } else {
    if (e.filterTextOuter)
      e.sectionHeader.parentNode.appendChild(e.filterTextOuter);
    e.sectionHeader.parentNode.appendChild(e.sectionRoot);
  }
  if (e.sectionExpander)
    e.sectionExpander.onclick = (t) => {
      toggleSectionExpansion(e.sectionRoot, e.sectionHeader, e.sectionBody);
    };
  if (t) {
    while (t.childNodes.length) {
      var i = t.childNodes[0];
      if (i.isResizer) {
        t.removeChild(i);
      } else {
        e.sectionHeader.appendChild(i);
      }
    }
  }
  e.panelDiv.layoutChanged(e.panelDiv);
  if (t) {
    savePanelsConfiguration();
  }
}
function restorePanelConfiguration(e, t) {
  var o = e.offsetHeight;
  isRestoringPanelConfigurations = true;
  try {
    t.forEach((t) => {
      switch (t) {
        case "项目管理器":
          createFileExplorer(e);
          break;
        case "打开":
          createOpenEditors(e);
          break;
        case "调用栈":
          createCallStackPanel(e);
          break;
        case "变量":
          createVariablesPanel(e);
          break;
        case "监视":
          createWatchPanel(e);
          break;
        case "调试控制台":
          createDebugConsole(e);
          break;
        case "问题":
          createProblemsPanel(e);
          break;
        case "大纲":
          createOutlinePanel(e);
          break;
        case "历史":
          createHistoryPanel(e);
          break;
        case "打包发布":
          createPackageManagerPanel(e);
          break;
      }
    });
  } catch (e) {}
  isRestoringPanelConfigurations = false;
}
function restorePanelsConfiguration() {
  isRestoringPanelConfigurations2 = true;
  leftPanel.addPanelSection(
    "{psuedo-begin}",
    leftPanel,
    "sectionHeader invisible2",
    true
  );
  rightPanel.addPanelSection(
    "{psuedo-begin}",
    rightPanel,
    "sectionHeader invisible2",
    true
  );
  centerInnerPanel.addPanelSection(
    "{psuedo-begin}",
    centerInnerPanel,
    "sectionHeader invisible2",
    true
  );
  if (panelLayout.panelsConfigration) {
    try {
      restorePanelConfiguration(
        leftPanel,
        panelLayout.panelsConfigration.leftPanel
      );
      restorePanelConfiguration(
        rightPanel,
        panelLayout.panelsConfigration.rightPanel
      );
      restorePanelConfiguration(
        centerInnerPanel,
        panelLayout.panelsConfigration.centerInnerPanel
      );
    } catch (e) {}
  }
  createFileExplorer(leftPanel);
  createOpenEditors(leftPanel);
  createOutlinePanel(leftPanel);
  createHistoryPanel(leftPanel);
  createProblemsPanel(leftPanel);
  createCallStackPanel(rightPanel);
  createVariablesPanel(rightPanel);
  createWatchPanel(rightPanel);
  createDebugConsole(centerInnerPanel);
  createPackageManagerPanel(rightPanel);
  leftPanel.addPanelSection(
    "{psuedo-end}",
    leftPanel,
    "sectionHeader invisible2",
    true
  );
  rightPanel.addPanelSection(
    "{psuedo-end}",
    rightPanel,
    "sectionHeader invisible2",
    true
  );
  centerInnerPanel.addPanelSection(
    "{psuedo-end}",
    centerInnerPanel,
    "sectionHeader invisible2",
    true
  );
  leftPanel.layoutChanged(leftPanel);
  rightPanel.layoutChanged(rightPanel);
  centerInnerPanel.layoutChanged(centerInnerPanel);
  isRestoringPanelConfigurations2 = false;
}
function savePanelsConfiguration() {
  if (isRestoringPanelConfigurations || isRestoringPanelConfigurations2) return;
  var e = [];
  for (let o = 0; o < leftPanel.childNodes.length; o++) {
    var t = leftPanel.childNodes[o];
    if (t.isRealPanelSection) {
      e.push(t.panelId);
      panelLayout[t.panelId] = t.sectionRoot.style.flexBasis
        ? parseInt(t.sectionRoot.style.flexBasis)
        : undefined;
      panelLayout[t.panelId + "-collapsed"] = t.classList.contains(
        "sectionHeaderCollapsed"
      )
        ? true
        : false;
    }
  }
  var o = [];
  for (let e = 0; e < rightPanel.childNodes.length; e++) {
    var t = rightPanel.childNodes[e];
    if (t.isRealPanelSection) {
      debugger;
      o.push(t.panelId);
      panelLayout[t.panelId] = t.sectionRoot.style.flexBasis
        ? parseInt(t.sectionRoot.style.flexBasis)
        : undefined;
      panelLayout[t.panelId + "-collapsed"] = t.classList.contains(
        "sectionHeaderCollapsed"
      )
        ? true
        : false;
    }
  }
  var n = [];
  for (let e = 0; e < centerInnerPanel.childNodes.length; e++) {
    var t = centerInnerPanel.childNodes[e];
    if (t.isRealPanelSection) {
      n.push(t.panelId);
      panelLayout[t.panelId] = t.style.minWidth
        ? parseInt(t.style.minWidth)
        : undefined;
      panelLayout[t.panelId + "-collapsed"] = t.innerDiv.classList.contains(
        "sectionHeaderCollapsed"
      )
        ? true
        : false;
    }
  }
  panelLayout.panelsConfigration = {
    leftPanel: e,
    rightPanel: o,
    centerInnerPanel: n,
  };
  panelLayout.leftPanel = parseInt(leftPanel.style.flexBasis);
  panelLayout.rightPanel = parseInt(rightPanel.style.flexBasis);
  panelLayout.centerInnerPanel = parseInt(centerInnerPanel.style.flexBasis);
  panelLayout.floatingToolWindows = floatingToolWindowsData;
  hostAppObject.SaveIDESetting("LAYOUT", JSON.stringify(panelLayout));
}
function initPanels() {
  leftPanel = document.getElementById("leftPanel");
  rightPanel = document.getElementById("rightPanel");
  centerInnerPanel = document.getElementById("centerInnerPanel");
  leftPanel.isVerticalPanel = true;
  rightPanel.isVerticalPanel = true;
  var e = document.getElementById("leftPanelResizer");
  e.onclick = (e) => {
    e.stopPropagation();
    return false;
  };
  e.onmousedown = (e) => {
    if (e.button === 0) {
      var t = leftPanel.offsetWidth;
      var o = (o) => {
        var n = t + (o.pageX - e.pageX);
        if (n < 50) return;
        leftPanel.style.flexBasis = n + "px";
        changedSize();
      };
      var n = (i) => {
        document.removeEventListener("mousemove", o);
        document.removeEventListener("mouseup", n);
        var r = t + (i.pageX - e.pageX);
        if (r < 50) return;
        leftPanel.style.flexBasis = r + "px";
        changedSize();
        savePanelsConfiguration();
      };
      document.addEventListener("mousemove", o);
      document.addEventListener("mouseup", n);
    }
  };
  var t = document.getElementById("rightPanelResizer");
  t.onclick = (e) => {
    e.stopPropagation();
    return false;
  };
  t.onmousedown = (e) => {
    if (e.button === 0) {
      var t = rightPanel.offsetWidth;
      var o = (o) => {
        var n = t - (o.pageX - e.pageX);
        if (n < 50) return;
        rightPanel.style.flexBasis = n + "px";
        changedSize();
      };
      var n = (i) => {
        document.removeEventListener("mousemove", o);
        document.removeEventListener("mouseup", n);
        var r = t - (i.pageX - e.pageX);
        if (r < 50) return;
        rightPanel.style.flexBasis = r + "px";
        changedSize();
        savePanelsConfiguration();
      };
      document.addEventListener("mousemove", o);
      document.addEventListener("mouseup", n);
    }
  };
  var o = document.getElementById("centerPanelResizer");
  o.onclick = (e) => {
    e.stopPropagation();
    return false;
  };
  o.onmousedown = (e) => {
    if (e.button === 0) {
      var t = centerInnerPanel.offsetHeight;
      var o = (o) => {
        var n = t - (o.pageY - e.pageY);
        if (n < 50) return;
        centerInnerPanel.style.flexBasis = n + "px";
        changedSize();
      };
      var n = (i) => {
        document.removeEventListener("mousemove", o);
        document.removeEventListener("mouseup", n);
        var r = t - (i.pageY - e.pageY);
        if (r < 50) return;
        centerInnerPanel.style.flexBasis = r + "px";
        changedSize();
        savePanelsConfiguration();
      };
      document.addEventListener("mousemove", o);
      document.addEventListener("mouseup", n);
    }
  };
  leftPanel.countOfSections = 0;
  leftPanel.addPanelSection = addVerticalPanelSection;
  leftPanel.layoutChanged = verticalPanelLayoutChanged;
  rightPanel.countOfSections = 0;
  rightPanel.addPanelSection = addVerticalPanelSection;
  rightPanel.layoutChanged = verticalPanelLayoutChanged;
  centerInnerPanel.countOfSections = 0;
  centerInnerPanel.addPanelSection = addHorizontalPanelSection;
  centerInnerPanel.layoutChanged = horizontalPanelLayoutChanged;
  var n = panelLayout["leftPanel"];
  if (n) {
    try {
      leftPanel.style.flexBasis = parseInt(n) + "px";
    } catch (e) {}
  }
  var i = panelLayout["rightPanel"];
  if (i) {
    try {
      rightPanel.style.flexBasis = parseInt(i) + "px";
    } catch (e) {}
  }
  var r = panelLayout["centerInnerPanel"];
  if (r) {
    try {
      centerInnerPanel.style.flexBasis = parseInt(r) + "px";
    } catch (e) {}
  }
}
function makeDraggablePanelHeader(e) {
  e.draggable = true;
  e.ondragstart = (t) => {
    onDragPanelSectionStart(t, e);
  };
  e.ondragover = (t) => {
    onDragPanelSectionHover(t, e, true);
  };
  e.ondragend = (t) => {
    onDragPanelSectionEnd(t, e);
  };
  e.ondrop = (e) => {
    onDragPanelSectionDropped(e);
  };
}
function updateInterPanelLinks(e) {
  var t = undefined;
  var o = undefined;
  for (let i = 0; i < e.childNodes.length; i++) {
    var n = e.childNodes[i];
    if (n.isPanelSection) {
      if (e.isVerticalPanel) {
        n.previousPanelSection = t;
        t = n;
        if (o) o.nextPanelSection = n;
        o = n;
      } else {
        n.innerDiv.previousPanelSection = t;
        t = n.innerDiv;
        if (o) o.nextPanelSection = n.innerDiv;
        o = n.innerDiv;
      }
    }
  }
}
function areAllSectionsFixedHeight(e) {
  for (let o = 0; o < e.childNodes.length; o++) {
    var t = e.childNodes[o];
    if (t.isRealPanelSection) {
      if (!t.sectionRoot.style.flexBasis) {
        return false;
      }
    }
  }
  return true;
}
function areAllSectionsFixedWidth(e) {
  for (let o = 0; o < e.childNodes.length; o++) {
    var t = e.childNodes[o];
    if (t.isRealPanelSection) {
      if (!t.style.minWidth) {
        return false;
      }
    }
  }
  return true;
}
function getPanelSectionsInfo(e, t) {
  var o = 0;
  var n = undefined;
  var i = undefined;
  var r = undefined;
  var s = undefined;
  for (let l = 0; l < e.childNodes.length; l++) {
    var a = e.childNodes[l];
    if (a.isPanelSection) {
      if (!r) r = a;
      n = a;
      o += 1;
      if (t) a.style = "";
    }
    if (a.isRealPanelSection) {
      s = a;
      if (t) a.style = "";
    }
    if (a.isEmptyPsuedoElement) {
      i = a;
    }
  }
  return {
    count: o,
    firstPanelSection: r,
    lastPanelSection: n,
    lastRealPanelSection: s,
    emptyPsuedoElement: i,
  };
}
function verticalPanelLayoutChanged(e) {
  var t = getPanelSectionsInfo(e, true);
  if (t.emptyPsuedoElement) {
    e.removeChild(t.emptyPsuedoElement);
  }
  if (!isRestoringPanelConfigurations && t.count == 2) {
    var o = createDOMElement(e, "div", "");
    o.isEmptyPsuedoElement = true;
    o.style.flexGrow = "1";
    o.style.flexShrink = "1";
    o.style.background =
      "repeating-linear-gradient( 45deg, #202021, #333335 10px, #4b4b4d 10px, #1a1a1a 20px)";
    e.insertBefore(o, t.lastPanelSection);
    o.ondragover = (e) => {
      if (currentDragType !== DRAG_PANEL_SECTION) return;
      e.preventDefault();
      e.dataTransfer.dropEffect = "move";
      currentDropZone = t.firstPanelSection;
      currentDropZone.resizerDiv.classList.add("panelMoveTarget");
      currentDropZone.classList.add("panelMoveTargetParent");
    };
    o.ondrop = (o) => {
      if (currentDragType !== DRAG_PANEL_SECTION) return;
      o.preventDefault();
      assignToPanel(undefined, startDropZone, e, t.lastPanelSection);
    };
  }
  updateInterPanelLinks(e);
  if (
    !isRestoringPanelConfigurations &&
    t.lastRealPanelSection &&
    areAllSectionsFixedHeight(e)
  ) {
    t.lastRealPanelSection.sectionRoot.style.flexGrow = "1";
    t.lastRealPanelSection.sectionRoot.style.flexShrink = "1";
    t.lastRealPanelSection.sectionRoot.style.flexBasis = "";
  }
  savePanelsConfiguration();
}
function horizontalPanelLayoutChanged(e) {
  var t = getPanelSectionsInfo(e, false);
  if (t.emptyPsuedoElement) {
    e.removeChild(t.emptyPsuedoElement);
  }
  if (!isRestoringPanelConfigurations && !t.lastRealPanelSection) {
    var o = createDOMElement(e, "div", "");
    o.isEmptyPsuedoElement = true;
    o.style.flexGrow = "1";
    o.style.flexShrink = "1";
    o.style.background =
      "repeating-linear-gradient( 45deg, #202021, #333335 10px, #4b4b4d 10px, #1a1a1a 20px)";
    e.insertBefore(o, t.lastPanelSection);
    o.ondragover = (e) => {
      e.preventDefault();
      e.dataTransfer.dropEffect = "move";
      currentDropZone = t.firstPanelSection;
      currentDropZone.resizerDiv.classList.add("panelMoveTarget");
      currentDropZone.classList.add("panelMoveTargetParent");
    };
    o.ondrop = (o) => {
      o.preventDefault();
      assignToPanel(undefined, startDropZone, e, t.lastPanelSection);
    };
  }
  if (
    !isRestoringPanelConfigurations &&
    t.lastRealPanelSection &&
    areAllSectionsFixedWidth(e)
  ) {
    t.lastRealPanelSection.style.flexGrow = "1";
    t.lastRealPanelSection.style.flexShrink = "1";
    t.lastRealPanelSection.style.minWidth = "";
    t.lastRealPanelSection.style.maxWidth = "";
  }
  updateInterPanelLinks(e);
  savePanelsConfiguration();
}
function addVerticalPanelSection(e, t, o, n, i) {
  t.countOfSections++;
  var r = createDOMElement(t, "div", o);
  if (i) {
    t.insertBefore(r, i);
  }
  if (!n) r.isRealPanelSection = true;
  r.isPanelSection = true;
  updateInterPanelLinks(t);
  if (i && r.previousPanelSection) {
    if (r.previousPanelSection.sectionRoot) {
      r.previousPanelSection.sectionRoot.style = "";
    }
  }
  r.panelId = e;
  r.panelDiv = t;
  var s = panelLayout[e];
  var a = panelLayout[e + "-collapsed"];
  if (s || a) {
    r.restoreCustomSize = () => {
      try {
        if (s) {
          r.sectionRoot.style.flexBasis = parseInt(s) + "px";
          r.sectionRoot.style.flexGrow = "0";
        }
        if (a) {
          r.sectionRoot.classList.add("sectionHidden");
          r.classList.add("sectionHeaderCollapsed");
        }
      } catch (e) {}
    };
  }
  if (!t.isToolWindow) {
    var l = createDOMElement(r, "div", "paneResizerVertical");
    l.isResizer = true;
    r.resizerDiv = l;
    l.onclick = (e) => {
      e.stopPropagation();
      e.preventDefault();
      return false;
    };
    l.ondblclick = (e) => {
      r.previousPanelSection.sectionRoot.style = "";
      r.sectionRoot.style = "";
      savePanelsConfiguration();
      e.stopPropagation();
      e.preventDefault();
      return false;
    };
    l.onmousedown = (e) => {
      if (e.button === 0) {
        var o = r.previousPanelSection.sectionRoot.clientHeight;
        var n = r.sectionRoot.clientHeight;
        var i = (t) => {
          var i = o + (t.pageY - e.pageY);
          var s = n - (t.pageY - e.pageY);
          if (i < 0 || s < 0) return;
          r.previousPanelSection.sectionRoot.style.flexBasis = i + "px";
          r.previousPanelSection.sectionRoot.style.flexGrow = "0";
          r.previousPanelSection.sectionRoot.style.flexShrink = "0";
          r.sectionRoot.style.flexBasis = s + "px";
          r.sectionRoot.style.flexGrow = "0";
          r.sectionRoot.style.flexShrink = "0";
        };
        var s = (a) => {
          document.removeEventListener("mousemove", i);
          document.removeEventListener("mouseup", s);
          var l = o + (a.pageY - e.pageY);
          var d = n - (a.pageY - e.pageY);
          if (l < 0 || d < 0) return;
          r.previousPanelSection.sectionRoot.style.flexBasis = l + "px";
          r.previousPanelSection.sectionRoot.style.flexGrow = "0";
          r.previousPanelSection.sectionRoot.style.flexShrink = "0";
          r.sectionRoot.style.flexBasis = d + "px";
          r.sectionRoot.style.flexGrow = "0";
          r.sectionRoot.style.flexShrink = "0";
          t.layoutChanged(t);
        };
        document.addEventListener("mousemove", i);
        document.addEventListener("mouseup", s);
        e.stopPropagation();
        e.preventDefault();
        return false;
      }
    };
  }
  if (!t.isToolWindow) {
    makeDraggablePanelHeader(r);
  }
  return r;
}
function addHorizontalPanelSection(e, t, o, n, i) {
  t.countOfSections++;
  var r = createDOMElement(
    t,
    "div",
    "centerInnerPanelColumn " + (n ? "isPsuedo" : "")
  );
  if (!n) r.isRealPanelSection = true;
  r.isPanelSection = true;
  if (i) t.insertBefore(r, i);
  var s = createDOMElement(r, "div", o);
  s.isPanelSection = true;
  r.panelId = e;
  r.innerDiv = s;
  s.panelId = e;
  s.panelDiv = t;
  updateInterPanelLinks(t);
  var a = panelLayout[e];
  var l = panelLayout[e + "-collapsed"];
  if (a || l) {
    s.restoreCustomSize = () => {
      try {
        if (a) {
          r.style.minWidth = parseInt(a) + "px";
          r.style.maxWidth = parseInt(a) + "px";
          r.style.flexGrow = "0";
        }
        if (l) {
        }
      } catch (e) {}
    };
  }
  if (t.countOfSections > 1) {
    var d = createDOMElement(r, "div", "paneResizerHorizontal");
    d.isResizer = true;
    s.resizerDiv = d;
    d.onclick = (e) => {
      e.stopPropagation();
      return false;
    };
    d.ondblclick = (e) => {
      s.previousPanelSection.parentNode.style = "";
      r.style = "";
      savePanelsConfiguration();
      e.stopPropagation();
      return false;
    };
    d.onmousedown = (e) => {
      if (e.button === 0) {
        var o = s.previousPanelSection.parentNode.offsetWidth;
        var n = r.offsetWidth;
        var i = (t) => {
          var i = o + (t.pageX - e.pageX);
          var a = n - (t.pageX - e.pageX);
          if (i < 0 || a < 0) return;
          s.previousPanelSection.parentNode.style.minWidth = i + "px";
          s.previousPanelSection.parentNode.style.maxWidth = i + "px";
          r.style.minWidth = a + "px";
          r.style.maxWidth = a + "px";
        };
        var a = (l) => {
          document.removeEventListener("mousemove", i);
          document.removeEventListener("mouseup", a);
          var d = o + (l.pageX - e.pageX);
          var c = n - (l.pageX - e.pageX);
          if (d < 0 || c < 0) return;
          s.previousPanelSection.parentNode.style.minWidth = d + "px";
          s.previousPanelSection.parentNode.style.maxWidth = d + "px";
          r.style.minWidth = c + "px";
          r.style.maxWidth = c + "px";
          t.layoutChanged(t);
        };
        document.addEventListener("mousemove", i);
        document.addEventListener("mouseup", a);
        e.stopPropagation();
        e.preventDefault();
        return false;
      }
    };
  }
  makeDraggablePanelHeader(s);
  return s;
}
function toggleSectionExpansion(e, t, o) {
  if (e.classList.contains("sectionHidden")) {
    e.classList.remove("sectionHidden");
    t.classList.remove("sectionHeaderCollapsed");
    savePanelsConfiguration();
  } else {
    e.classList.add("sectionHidden");
    t.classList.add("sectionHeaderCollapsed");
    savePanelsConfiguration();
  }
}
function initProblemsPanel() {}
var problemsPanel = undefined;
var problemsPanelOptions = { showErrors: true, showWarnings: true };
const PROBLEMSPANEL_CUSTOMPROPERTY_TYPE = 0;
const PROBLEMSPANEL_CUSTOMPROPERTY_TYPE0_FILEHEADER_URL = 1;
const PROBLEMSPANEL_CUSTOMPROPERTY_TYPE1_DIAGNOSTIC_LINENUM = 1;
const PROBLEMSPANEL_CUSTOMPROPERTY_TYPE1_DIAGNOSTIC_CHARNUM = 2;
const PROBLEMSPANEL_CUSTOMPROPERTY_TYPE1_DIAGNOSTIC_SEVERITY = 3;
const _PROBLEMSPANEL_CUSTOMPROPERTY_MAXCOUNT = 4;
const PROBLEMSPANEL_CUSTOMPROPERTY_TYPE0_FILEHEADER = 0;
const PROBLEMSPANEL_CUSTOMPROPERTY_TYPE1_DIAGNOSTIC = 1;
function generateCopyPasteTextForProblem(e, t) {
  if (!e) return;
  var o = e
    .getParentNodeInfo()
    .getCustomData(PROBLEMSPANEL_CUSTOMPROPERTY_TYPE0_FILEHEADER_URL);
  if (!o) return;
  var n = e.getCustomData(PROBLEMSPANEL_CUSTOMPROPERTY_TYPE);
  let i;
  switch (n) {
    case PROBLEMSPANEL_CUSTOMPROPERTY_TYPE0_FILEHEADER:
      return;
    case PROBLEMSPANEL_CUSTOMPROPERTY_TYPE1_DIAGNOSTIC:
      i = e.getCaption();
      break;
  }
  var r = e.getCustomData(
    PROBLEMSPANEL_CUSTOMPROPERTY_TYPE1_DIAGNOSTIC_SEVERITY
  );
  var s = e.getCustomData(
    PROBLEMSPANEL_CUSTOMPROPERTY_TYPE1_DIAGNOSTIC_LINENUM
  );
  var a = e.getCustomData(
    PROBLEMSPANEL_CUSTOMPROPERTY_TYPE1_DIAGNOSTIC_CHARNUM
  );
  if (t && r !== 1) return;
  i =
    (r === 1 ? "{ERROR} " : "{WARNING} ") +
    o +
    " [" +
    (s + 1) +
    "," +
    (a + 1) +
    "]: " +
    i;
  return i;
}
class _problemsPanel {
  constructor(e, t) {
    var o = _PROBLEMSPANEL_CUSTOMPROPERTY_MAXCOUNT;
    this.id = 0;
    this.tree = new virtualTreeView(
      e,
      "问题",
      "twinbasic-problems:",
      false,
      o,
      "--problems",
      t
    );
    this.tree.showFolderIcons = false;
    this.tree.autoExpandOnSelect = false;
    this.tree.showTooltips = true;
    this.tree.additionalFolderClassNames = "testTree";
    this.tree.emptyFolderText = "";
    this.tree.renderDomNode = (e) => {
      var t = e.getCustomData(PROBLEMSPANEL_CUSTOMPROPERTY_TYPE);
      let o;
      switch (t) {
        case PROBLEMSPANEL_CUSTOMPROPERTY_TYPE0_FILEHEADER:
          if (e.isExpanded()) {
            o =
              "<div class='problemNodeGroupIcon iconCollapse14' onclick='toggleProblemNode(event)'></div>";
          } else {
            o =
              "<div class='problemNodeGroupIcon iconExpand14' onclick='toggleProblemNode(event)'></div>";
          }
          var n = e.getCustomData(
            PROBLEMSPANEL_CUSTOMPROPERTY_TYPE0_FILEHEADER_URL
          );
          return (
            "<div class='problemNodeGroup' title='" +
            n +
            "'>" +
            o +
            e.getCaption() +
            "</div>"
          );
        case PROBLEMSPANEL_CUSTOMPROPERTY_TYPE1_DIAGNOSTIC:
          var i = e.getCustomData(
            PROBLEMSPANEL_CUSTOMPROPERTY_TYPE1_DIAGNOSTIC_SEVERITY
          );
          var r = e.getCustomData(
            PROBLEMSPANEL_CUSTOMPROPERTY_TYPE1_DIAGNOSTIC_LINENUM
          );
          var s = e.getCustomData(
            PROBLEMSPANEL_CUSTOMPROPERTY_TYPE1_DIAGNOSTIC_CHARNUM
          );
          if (i === 1) {
            o = "<div class='problemNodeIcon errorIconRed'></div>";
          } else {
            o = "<div class='problemNodeIcon warningIconYellow'></div>";
          }
          return (
            "<div class='problemNodeItem'>" +
            o +
            e.getCaption() +
            "<div class='problemNodePos'>[" +
            (r + 1) +
            "," +
            (s + 1) +
            "]</div>" +
            "</div>"
          );
      }
    };
    this.tree.onDblClickNode = (e) => {
      var t = e.getCustomData(PROBLEMSPANEL_CUSTOMPROPERTY_TYPE);
      switch (t) {
        case PROBLEMSPANEL_CUSTOMPROPERTY_TYPE0_FILEHEADER:
          e.toggleExpanded();
          this.tree.updateVisibleNodesList();
          break;
        case PROBLEMSPANEL_CUSTOMPROPERTY_TYPE1_DIAGNOSTIC:
          var o = e
            .getParentNodeInfo()
            .getCustomData(PROBLEMSPANEL_CUSTOMPROPERTY_TYPE0_FILEHEADER_URL);
          var n = e.getCustomData(
            PROBLEMSPANEL_CUSTOMPROPERTY_TYPE1_DIAGNOSTIC_LINENUM
          );
          var i = e.getCustomData(
            PROBLEMSPANEL_CUSTOMPROPERTY_TYPE1_DIAGNOSTIC_CHARNUM
          );
          var r = fs.tree.resolvePath("twinbasic:" + o);
          openEditors.openFile(r, false, false, false, n + 1, i + 1);
          break;
      }
    };
    this.tree.onClickNode = (e) => {
      var t = e.getCustomData(PROBLEMSPANEL_CUSTOMPROPERTY_TYPE);
      switch (t) {
        case PROBLEMSPANEL_CUSTOMPROPERTY_TYPE1_DIAGNOSTIC:
          var o = e
            .getParentNodeInfo()
            .getCustomData(PROBLEMSPANEL_CUSTOMPROPERTY_TYPE0_FILEHEADER_URL);
          var n = e.getCustomData(
            PROBLEMSPANEL_CUSTOMPROPERTY_TYPE1_DIAGNOSTIC_LINENUM
          );
          var i = e.getCustomData(
            PROBLEMSPANEL_CUSTOMPROPERTY_TYPE1_DIAGNOSTIC_CHARNUM
          );
          var r = fs.tree.resolvePath("twinbasic:" + o);
          openEditors.openFile(
            r,
            liveIDEOptions["previewDocs"] ? true : false,
            false,
            false,
            n + 1,
            i + 1
          );
          break;
      }
    };
    this.tree.onRightClickNode = (e, t, o) => {
      showContextMenu(undefined, t, o, [
        {
          name: "复制",
          action: () => {
            var t = generateCopyPasteTextForProblem(e);
            if (t === undefined) t = "";
            navigator.clipboard.writeText(t);
          },
        },
        {
          name: "Copy All",
          action: () => {
            let e =
              "twinBASIC (" + tbVersionInfo + ") compilation error report:\r\n";
            var t = 1;
            while (1) {
              t = this.tree.view.data.getNextVisibleNode2(t, false, true);
              if (!t) break;
              var o = this.tree.view.data.generateNodeInfo(t);
              var n = generateCopyPasteTextForProblem(o);
              if (n) e += " " + n + "\r\n";
            }
            navigator.clipboard.writeText(e);
          },
        },
        {
          name: "Copy All Errors",
          action: () => {
            let e =
              "twinBASIC (" + tbVersionInfo + ") compilation error report:\r\n";
            var t = 1;
            while (1) {
              t = this.tree.view.data.getNextVisibleNode2(t, false, true);
              if (!t) break;
              var o = this.tree.view.data.generateNodeInfo(t);
              var n = generateCopyPasteTextForProblem(o, true);
              if (n) e += " " + n + "\r\n";
            }
            navigator.clipboard.writeText(e);
          },
        },
        {},
        {
          name: "Collapse all",
          action: () => {
            var e = 1;
            while (1) {
              e = this.tree.view.data.getNextVisibleNode2(e, false, true);
              if (!e) break;
              var t = this.tree.view.data.generateNodeInfo(e);
              var o = t.getCustomData(PROBLEMSPANEL_CUSTOMPROPERTY_TYPE);
              if (o == PROBLEMSPANEL_CUSTOMPROPERTY_TYPE0_FILEHEADER) {
                t.collapse();
              }
            }
          },
        },
        {
          name: "Expand all",
          action: () => {
            var e = 1;
            while (1) {
              e = this.tree.view.data.getNextVisibleNode2(e, false, true);
              if (!e) break;
              var t = this.tree.view.data.generateNodeInfo(e);
              var o = t.getCustomData(PROBLEMSPANEL_CUSTOMPROPERTY_TYPE);
              if (o == PROBLEMSPANEL_CUSTOMPROPERTY_TYPE0_FILEHEADER) {
                t.expand();
              }
            }
          },
        },
      ]);
    };
    this.tree.init();
    if (!t) {
      var n = createDOMElement(this.tree.sectionHeader, "div", "flexDiv", "");
      n.innerHTML =
        "<div id='statusErrors' title='Total Error Count' onclick='toggleProblemsErrors()'><div class='statusIcon errorIcon'></div><div id='errorCount'>0</div></div>" +
        "<div id='statusWarnings' title='Total Warning Count' onclick='toggleProblemsWarnings()'><div class='statusIcon warningIcon'></div><div id='warningCount'>0</div></div>";
    }
    this.tree.finishedInit();
  }
  syncFileProblems(e) {
    var t = false;
    this.tree.view.data.startMultiUpdate();
    try {
      var o = () => {
        var o =
          e.cachedDiagnostics_errorCount + e.cachedDiagnostics_warningCount;
        if (!e.problemNode) {
          if (o == 0) {
            t = true;
            return;
          }
          e.problemNode = this.tree.view.data.addSubNode(
            this.tree.view.data.rootFolder,
            e.name,
            0,
            e.getFullPath()
          );
        } else {
          if (o == 0) {
            this.tree.view.data.deleteNode(e.problemNode);
            e.problemNode = undefined;
            return;
          } else {
            this.tree.view.data.deleteNodeChildren(e.problemNode);
          }
        }
        if (e.cachedDiagnostics) {
          e.cachedDiagnostics.forEach((t) => {
            this.tree.view.data.addSubNode(
              e.problemNode,
              t.message,
              1,
              t.range.start.line,
              t.range.start.character,
              t.severity,
              t.severity == 1,
              t.severity == 2
            );
          });
        }
      };
      o();
    } catch (e) {}
    if (t) {
      this.tree.view.data.endMultiUpdateNoChanges();
    } else {
      this.tree.view.data.endMultiUpdate();
    }
  }
}
function toggleProblemNode(e) {
  problemsPanel.tree.view.toggleExpanded(
    e.target.parentNode.parentNode.nodeVisibleIndex
  );
  e.stopPropagation();
}
function createProblemsPanel(e, t) {
  if (problemsPanel) return problemsPanel;
  problemsPanel = new _problemsPanel(e, t);
}
function toggleProblemsErrors(e) {
  problemsPanelOptions.showErrors = problemsPanelOptions.showErrors
    ? false
    : true;
  resyncProblemsPanelOptions();
}
function toggleProblemsWarnings(e) {
  problemsPanelOptions.showWarnings = problemsPanelOptions.showWarnings
    ? false
    : true;
  resyncProblemsPanelOptions();
}
function resyncProblemsPanelOptions() {
  if (problemsPanelOptions.showErrors) {
    statusErrorsDiv.classList.remove("statusUnselected");
    problemsPanel.tree.view.data.hideGroup1 = false;
  } else {
    statusErrorsDiv.classList.add("statusUnselected");
    problemsPanel.tree.view.data.hideGroup1 = true;
  }
  if (problemsPanelOptions.showWarnings) {
    statusWarningsDiv.classList.remove("statusUnselected");
    problemsPanel.tree.view.data.hideGroup2 = false;
  } else {
    statusWarningsDiv.classList.add("statusUnselected");
    problemsPanel.tree.view.data.hideGroup2 = true;
  }
  problemsPanel.tree.view.data.updateVisibleNodesList();
}
var hostAppObject;
var hostAppObject_packagesList;
var hostAppObject_projectsList;
var hostAppObject_samplesList;
var hostAppObject_recentsList;
var hostAppObject_setting_FORMS_leftSidePanelWidth;
var hostAppObject_setting_FORMS_rightSidePanelWidth;
var hostAppObject_setting_FORMS_windowsPalette;
var ideSettings = {
  FORMS: {
    init: async () => {
      hostAppObject_setting_FORMS_leftSidePanelWidth = parseNumeric(
        await hostAppObject.GetIDESetting("FORMS_leftSidePanelWidth")
      );
      hostAppObject_setting_FORMS_rightSidePanelWidth = parseNumeric(
        await hostAppObject.GetIDESetting("FORMS_rightSidePanelWidth")
      );
      hostAppObject_setting_FORMS_windowsPalette = parseJson(
        await hostAppObject.GetIDESetting("FORMS_windowsPalette")
      );
    },
    get_leftSidePanelWidth: () =>
      hostAppObject_setting_FORMS_leftSidePanelWidth,
    put_leftSidePanelWidth: async (e) => {
      e = parseNumeric(e);
      await hostAppObject.SaveIDESetting("FORMS_leftSidePanelWidth", e);
      hostAppObject_setting_FORMS_leftSidePanelWidth = e;
    },
    get_rightSidePanelWidth: () =>
      hostAppObject_setting_FORMS_rightSidePanelWidth,
    put_rightSidePanelWidth: async (e) => {
      e = parseNumeric(e);
      await hostAppObject.SaveIDESetting("FORMS_rightSidePanelWidth", e);
      hostAppObject_setting_FORMS_rightSidePanelWidth = e;
    },
    get_windowsPalette: () => hostAppObject_setting_FORMS_windowsPalette,
    put_windowsPalette: async (e) => {
      await hostAppObject.SaveIDESetting(
        "FORMS_windowsPalette",
        JSON.stringify(e)
      );
      hostAppObject_setting_FORMS_windowsPalette = e;
    },
  },
};
async function initHostAppObject(e) {
  hostAppObject = chrome.webview.hostObjects.hostAppObject;
  if (isDebugMode) await hostAppObject.OpenDevTools("ignore");
  hostAppObject_packagesList = (
    await hostAppObject.GetPackagesList("ignoreMe")
  ).split("?");
  hostAppObject_projectsList = (
    await hostAppObject.GetProjectsList("ignoreMe")
  ).split("?");
  hostAppObject_samplesList = (
    await hostAppObject.GetSamplesList("ignoreMe")
  ).split("?");
  await ideSettings.FORMS.init();
  e();
}
async function GetPackageFileData(e, t) {
  var o = await hostAppObject.GetPackageData(e);
  if (Array.isArray(o)) {
    bufferToBase64Async(new Uint8Array(o), (e) => {
      t(e);
    });
  } else {
    alert("内部错误; 无法加载内置包 " + e);
  }
}
async function openProject() {
  var e = await hostAppObject.OpenProject("ignoreMe");
  if (e && e.length > 0) {
    if (e.substring(e.length - 4).toLowerCase() === ".vbp") {
      root.loadProjectVBP(e);
    } else {
      root.loadProject(e);
    }
  }
}
async function openProjectVBP() {
  var e = await hostAppObject.OpenProjectVBP("ignoreMe");
  if (e && e.length > 0) {
    root.loadProjectVBP(e);
  }
}
async function openProjectFromFolder() {
  var e = await hostAppObject.ChooseFolder(
    "选择现有twinBASIC项目文件夹...",
    ""
  );
  if (e && e.length > 0) {
    root.loadProjectFromFolder(e);
  }
}
function saveProject() {
  if (projectFilePath) {
    saveIcon.onclick();
  } else {
    saveProjectAs(() => {
      saveIcon.onclick();
    });
  }
}
async function saveProjectAs(e) {
  var t =
    fs.tree.rootFolder.entries[Object.keys(fs.tree.rootFolder.entries)[0]];
  var o = await hostAppObject.SaveProjectAs(t.name);
  if (o && o.length > 0) {
    root.saveProjectAs(o, e);
  }
}
async function HostForceFocus() {
  await hostAppObject.ForceFocus("");
}
var isRestarting = false;
var allBookmarks = {};
var currentBookmarkDecorations = [];
var searchInsidePackages = false;
var searchCaseSensitive = false;
var searchWholeWordOnly = false;
function clearAllCurrentEditorBookmarks() {
  currentBookmarkDecorations.forEach((e) => {
    editor.deltaDecorations(e, []);
  });
  currentBookmarkDecorations = [];
}
function clearAllBookmarks(e, t) {
  if (t) {
    allBookmarks = {};
  } else {
    delete allBookmarks[e];
  }
  resyncBookmarks(e);
}
function toggleBookmark(e, t) {
  if (allBookmarks[e] === undefined) {
    allBookmarks[e] = {};
  }
  if (allBookmarks[e][t]) {
    delete allBookmarks[e][t];
  } else {
    allBookmarks[e][t] = true;
  }
  resyncBookmarks(e);
}
function moveBookmarks(e, t) {
  e = e.replace("twinbasic:", "");
  t = t.replace("twinbasic:", "");
  allBookmarks[t] = allBookmarks[e];
  allBookmarks[e] = {};
}
function deleteBookmarks(e) {
  e = e.replace("twinbasic:", "");
  allBookmarks[e] = {};
}
function getNextUriToSearch(e) {
  var t = e;
  var o = false;
  var n = false;
  do {
    fs.tree.rootFolder.enumerateContent(true, (i) => {
      var r = i.getFullPath();
      if (o) {
        t = r;
        n = true;
        return false;
      }
      if (r == e) {
        o = true;
      }
      return true;
    });
  } while (!n);
  return t;
}
function getPrevUriToSearch(e) {
  var t = e;
  var o = undefined;
  fs.tree.rootFolder.enumerateContent(true, (n) => {
    var i = n.getFullPath();
    if (i == e) {
      t = o;
      return false;
    }
    o = i;
    return true;
  });
  if (t == undefined) {
    fs.tree.rootFolder.enumerateContent(true, (e) => {
      t = e.getFullPath();
      return true;
    });
  }
  return t;
}
function gotoNextBookmark(e, t) {
  var o = e;
  do {
    var n = allBookmarks[o];
    if (n) {
      var i = 99999999;
      Object.entries(n).forEach((e) => {
        e = parseInt(e);
        if (e > t) {
          if (e < i) {
            i = e;
          }
        }
      });
      if (i != 99999999) {
        var r = fs.tree.resolvePath("twinbasic:" + o);
        openEditors.openFile(r, false, false, false, i, 1);
        return;
      }
    }
    if (e == o && t == 0) {
      break;
    }
    o = getNextUriToSearch(o);
    t = 0;
  } while (true);
}
function gotoPrevBookmark(e, t) {
  var o = e;
  do {
    var n = allBookmarks[o];
    if (n) {
      var i = 0;
      Object.entries(n).forEach((e) => {
        e = parseInt(e);
        if (e < t) {
          if (e > i) {
            i = e;
          }
        }
      });
      if (i) {
        var r = fs.tree.resolvePath("twinbasic:" + o);
        openEditors.openFile(r, false, false, false, i, 1);
        return;
      }
    }
    if (e == o && t == 9999999999) {
      break;
    }
    o = getPrevUriToSearch(o);
    t = 9999999999;
  } while (true);
}
function resyncBookmarks(e) {
  if (e != openEditors.selectedEditorNode.fileNode.getFullPath()) return;
  clearAllCurrentEditorBookmarks();
  if (allBookmarks[e] === undefined) {
    return;
  }
  var t = allBookmarks[e];
  Object.entries(t).forEach((e) => {
    e = parseInt(e);
    currentBookmarkDecorations.push(
      editor.deltaDecorations(
        [],
        [
          {
            range: new monaco.Range(e, 1, e, 1),
            options: {
              glyphMarginClassName: "marginGlyph bookmarkActiveGlyph",
            },
          },
        ]
      )
    );
  });
}
var defaultMetaState = {
  rootFolder: "/MyProject",
  fs_expandedFolders: ["/MyProject", "/MyProject/Sources/"],
  variables_expandedCache: { "/Locals": true },
};
async function HostSaveProjectMetaState(e) {
  try {
    var t = projectFilePath;
    hostAppObject.SaveProjectMetaState(t, e);
  } catch (e) {}
}
function saveProjectMetaState(e) {
  var t =
    fs.tree.rootFolder.entries[Object.keys(fs.tree.rootFolder.entries)[0]];
  var o = t.getFullPath();
  var n = {
    rootFolder: o,
    fs_expandedFolders: fs.getExpandedFolders(),
    openEditors: openEditors.getOpenEditors(),
    debugConsoleEntryHistory: debugConsoleEntryHistory,
    variables_expandedCache: variablesPanel.expandedCache,
    watches: watchPanel.getWatches(),
    watches_expandedCache: watchPanel.expandedCache,
    outlinePanelOptions: outlinePanelOptions,
    debugPanelOptions: debugPanelOptions,
    problemsPanelOptions: problemsPanelOptions,
    history: persistHistoryPanel(),
    toolWindows: getToolWindowsPersistanceData(),
    bookmarks: allBookmarks,
    searchInsidePackages: searchInsidePackages,
    searchCaseSensitive: searchCaseSensitive,
    searchWholeWordOnly: searchWholeWordOnly,
  };
  if (e) {
    fs.createFileUTF8(o + "/.meta", JSON.stringify(n, undefined, "\t"), e);
  } else {
    if (projectFilePath) {
      HostSaveProjectMetaState(JSON.stringify(n, undefined, "\t"));
    }
  }
}
setInterval(saveProjectMetaState, 1e4);
function doneLoadingMetaState() {
  hideModalProgressIndicator();
  if (buildConfigSelector.value === "nocompile") {
    var e = createDOMElement(
      undefined,
      "div",
      "simpleMsgBox",
      "SafeMode is designed to give you access to the file system\nof your project, without starting all of the associated compiler services.\n\nUse this mode to investigate / fix / recover your code before saving\nand restarting in normal mode."
    );
    showModalDialog(e, [{ caption: "确定", onclick: hideModalDialog }]);
  }
  HostForceFocus();
}
async function loadProjectMetaState() {
  var e = projectFilePath;
  if (projectFilePath) {
    var t = await hostAppObject.LoadProjectMetaState(e);
    if (t) {
      try {
        let e = JSON.parse(t);
        restoreProjectState(e, () => {
          doneLoadingMetaState();
        });
        return;
      } catch (e) {
        debugOutputLine("IDE: failed to restore project state from host data.");
      }
    }
  }
  let o =
    fs.tree.rootFolder.entries[Object.keys(fs.tree.rootFolder.entries)[0]];
  let n = o.entries[".meta"];
  if (n) {
    fs.readFile(n, (e, t) => {
      let o = new TextDecoder();
      let n = o.decode(t);
      let i = JSON.parse(n);
      restoreProjectState(i, () => {
        doneLoadingMetaState();
      });
    });
  } else {
    restoreProjectState(defaultMetaState, () => {
      doneLoadingMetaState();
    });
  }
}
function restoreProjectState(e, t) {
  var o = e.rootFolder;
  var n =
    fs.tree.rootFolder.entries[Object.keys(fs.tree.rootFolder.entries)[0]];
  try {
    e.fs_expandedFolders.forEach((e) => {
      var t = e.substring(o.length);
      if (t.length === 0) {
        n.expand();
      } else {
        t = t.substring(1);
        var i = n.resolvePath(t);
        if (i && i.isFolder) {
          i.expand();
        }
      }
    });
  } catch (e) {}
  if (!isRestarting) {
    if (liveIDEOptions["preserveCodeEditorStateOnReopen"]) {
      try {
        var i = 0;
        var r = undefined;
        e.openEditors.forEach((e) => {
          var t = e.uri;
          var s = e.state;
          var a = t.substring(o.length);
          a = a.substring(1);
          if (e.isSelected) r = a;
          var l = n.resolvePath(a);
          if (l && !l.isFolder) {
            i++;
            openEditors.openFile(
              l,
              false,
              false,
              false,
              undefined,
              undefined,
              undefined,
              () => {
                i--;
                if (i === 0) {
                  try {
                    if (r) {
                      let e = n.resolvePath(r);
                      if (e) {
                        openEditors.openFile(e);
                      }
                    }
                  } catch (e) {}
                }
              },
              s
            );
          }
        });
      } catch (e) {}
    }
    try {
      if (Array.isArray(e.debugConsoleEntryHistory)) {
        debugConsoleEntryHistory = e.debugConsoleEntryHistory;
      }
    } catch (e) {}
    try {
      if (typeof e.variables_expandedCache === "object") {
        variablesPanel.expandedCache = e.variables_expandedCache;
      }
    } catch (e) {}
    try {
      if (typeof e.watches_expandedCache === "object") {
        watchPanel.expandedCache = e.watches_expandedCache;
      }
    } catch (e) {}
  }
  try {
    if (Array.isArray(e.watches)) {
      watchPanel.tree.rootFolder.muteRendering = true;
      e.watches.forEach((e) => {
        addNewWatchExpression(e);
      });
      watchPanel.tree.rootFolder.muteRendering = false;
      watchPanel.tree.rootFolder.renderEntries();
    }
  } catch (e) {}
  try {
    if (typeof e.outlinePanelOptions === "object") {
      outlinePanelOptions = e.outlinePanelOptions;
      outlinePanel.rebuildFilteredTypes();
    }
  } catch (e) {}
  try {
    if (typeof e.debugPanelOptions === "object") {
      debugPanelOptions = e.debugPanelOptions;
    }
    resyncDebugPanelOptions();
  } catch (e) {}
  try {
    if (typeof e.problemsPanelOptions === "object") {
      problemsPanelOptions = e.problemsPanelOptions;
    }
    resyncProblemsPanelOptions();
  } catch (e) {}
  try {
    if (typeof e.bookmarks === "object") {
      allBookmarks = e.bookmarks;
    }
  } catch (e) {}
  try {
    if (e.searchInsidePackages !== undefined) {
      searchInsidePackages = e.searchInsidePackages ? true : false;
    }
    if (e.searchCaseSensitive !== undefined) {
      searchCaseSensitive = e.searchCaseSensitive ? true : false;
    }
    if (e.searchWholeWordOnly !== undefined) {
      searchWholeWordOnly = e.searchWholeWordOnly ? true : false;
    }
  } catch (e) {}
  try {
    if (typeof e.history === "object") {
      restoreHistoryPanel(e.history);
    }
  } catch (e) {}
  try {
    if (typeof e.toolWindows === "object") {
      loadToolWindowsFromPersistanceData(e.toolWindows);
    }
  } catch (e) {}
  if (isRestarting) {
    try {
      openEditors.resyncToFileSystem();
    } catch (e) {}
    isRestarting = false;
  }
  t();
}
var lastCompilerStart_ideDataExecutionPrevention;
var lastCompilerStart_ideLargeAddressAware;
var lastCompilerStart_showAdvancedHoverInfo;
var lastCompilerStart_showHiddenMembers;
var lastCompilerStart_useHandlesImplementsSyntax;
var lastCompilerStart_showDebuggerMemUsage;
var problemReferences = [];
var g_CurrentProjectMajorVersion = undefined;
var g_CurrentProjectMinorVersion = undefined;
var g_CurrentProjectRevisionVersion = undefined;
var g_CurrentProjectBuildVersion = undefined;
var g_CurrentProjectIsPackage = undefined;
var g_CurrentProjectName = undefined;
var g_CurrentProjectDescription = undefined;
var g_CurrentProjectLicence = undefined;
var g_CurrentProjectVisibility = undefined;
var RequestInitialize = 0;
var RequestLoadProject = 1;
var RequestLoadProjectFromMemory = 2;
var RequestAllProjectsLoaded = 3;
var RequestProvidePackageFileData = 4;
var RequestSaveProjectAs = 5;
var RequestMultiUpdateStart = 6;
var RequestMultiUpdateEnd = 7;
var RequestImportProjectVBP = 8;
var RequestShutdown = 9;
var RequestWaitForSaveProjectCompletion = 10;
var RequestBringProcessToFront = 11;
var RequestTerminateProcess = 12;
var RequestImportFile = 13;
var RequestExportProject = 14;
var RequestImportProjectFolder = 15;
var RequestTerminate = 16;
var RequestShell = 17;
var RequestShellMuted = 18;
var RequestSaveFailedResponse = 19;
var RequestProgressLogSynchronousResponse = 20;
var RequestPreInitialize = 22;
var RequestExportFile = 23;
var RequestProvideMassagedSettingsResult = 24;
var RequestSetDebugMode = 25;
var RequestNotifyModalResult = 26;
var RequestNotifyModalResultString = 27;
var RequestNotifyModalResultVariant = 28;
var RequestNotifyModalResultFailed = 29;
var RequestQueueJob = 30;
var RequestLoadAddins = 31;
var RequestAddinsStateList = 32;
var RequestNotifyChangedActiveEditor = 33;
var ReverseRequestGetPackageFileData = 255;
var ReverseRequestSaveInMemoryProject = 254;
var ReverseRequestProjectIsDirtyState = 253;
var ReverseRequestSettingsFileChanged = 252;
var ReverseRequestIPC = 251;
var ReverseRequestKeyValidationResult = 250;
var ReverseRequestProcessStarted = 249;
var ReverseRequestProcessEnded = 248;
var ReverseRequestMsgBox = 247;
var ReverseRequestSaveFailed = 246;
var ReverseRequestProgressLogSynchronous = 245;
var ReverseRequestReferenceProblem = 244;
var ReverseRequestMassageSettings = 243;
var ReverseRequestAddInRequest = 242;
var responseCodeError_BadFileFormat = -3;
var responseCodeError_FileNotFound = -2;
var responseCodeError_Generic = -1;
var projectBuildPath = undefined;
var projectFilePath = undefined;
var projectIsDirty = false;
var projectIsLoaded = false;
var compilerPassKey = undefined;
var toolWindowId = 900;
var toolWindows = {};
var activeAddinWidgets = {};
function removeAllToolWindows() {
  for (const e in toolWindows) {
    toolWindows[e].selfRemove();
  }
  toolWindows = {};
  activeAddinWidgets = {};
}
function removeAllAddinWidgets() {
  for (const e in activeAddinWidgets) {
    activeAddinWidgets[e].selfRemove();
    debugger;
    delete toolWindows[e];
  }
  activeAddinWidgets = {};
}
function trackAddinWidgetMovements(e) {
  for (const r in activeAddinWidgets) {
    var t = activeAddinWidgets[r];
    var o = e.getModel().getDecorationRange(t.trackerDecoration);
    var n = o.startLineNumber;
    var i = o.startColumn;
    if (
      n != t.currentLineNumber ||
      (t.wholeLine == false && i != t.currentColumnNumber)
    ) {
      t.currentLineNumber = n;
      t.currentColumnNumber = i;
      if (!t.myZone) {
        e.layoutContentWidget(t.overlayWidget);
      } else {
        t.myZone.afterLineNumber = n;
        e.changeViewZones(function (e) {
          e.layoutZone(t.viewZoneId);
        });
      }
      if (t.shadowDom.rootEventHandler.move) {
        t.shadowDom.rootEventHandler.move({
          target: { id: t.shadowDom.rootEventHandler.id },
          lineNumber: n,
        });
      }
    }
  }
}
function saveFloatingToolWindowPosition(e) {
  if (e.persistenceId.length > 0) {
    floatingToolWindowsData[e.persistenceId] = {};
    floatingToolWindowsData[e.persistenceId].left = parseInt(e.style.left);
    floatingToolWindowsData[e.persistenceId].top = parseInt(e.style.top);
    if (e.style.width)
      floatingToolWindowsData[e.persistenceId].width = parseInt(e.style.width);
    if (e.style.height)
      floatingToolWindowsData[e.persistenceId].height = parseInt(
        e.style.height
      );
    savePanelsConfiguration();
  }
}
var addInEvents = {
  createToolbarSplitter(e) {
    try {
      var t = document.createElement("div");
      t.className = "toolbarSplitter";
      rootMenu2.appendChild(t);
      addinAlterationsAdditions.push(t);
    } catch (e) {
      return;
    }
  },
  createToolbarIcon(e) {
    try {
      var t = document.createElement("div");
      t.id = "addinButton-" + e.id;
      t.className = "icon iconType1";
      if (e.imageData) {
        t.innerHTML = "";
        t.style.backgroundImage =
          "url('data:image;base64," + e.imageData + "')";
        t.classList.remove("iconTextOnly");
        t.classList.add("iconCenter");
      } else {
        t.innerHTML = e.caption;
        t.style.backgroundImage = "";
        t.classList.add("iconTextOnly");
        t.classList.remove("iconCenter");
      }
      t.title = e.caption;
      t.onclick = () => {
        root.sendJobInfo(e.threadJobs, e.threadJob);
      };
      rootMenu2.appendChild(t);
      addinAlterationsAdditions.push(t);
    } catch (e) {
      return;
    }
  },
  updateToolbarIcon(e) {
    try {
      var t = document.getElementById("addinButton-" + e.id);
      if (e.imageData) {
        t.innerHTML = "";
        t.style.backgroundImage =
          "url('data:image;base64," + e.imageData + "')";
        t.classList.remove("iconTextOnly");
        t.classList.add("iconCenter");
      } else {
        t.innerHTML = e.caption;
        t.style.backgroundImage = "";
        t.classList.add("iconTextOnly");
        t.classList.remove("iconCenter");
      }
      t.title = e.caption;
    } catch (e) {
      return;
    }
  },
  showMessageBox(e) {
    try {
      showModalMsgWithButtons(e.message, e.buttons, e.title, e.waitData);
    } catch (t) {
      root.sendModalResultFailed(e.waitData);
      return;
    }
  },
  registerKeyboardShortcut(e) {
    try {
      registerAddInKeyboardShortcut(e.keyString, () => {
        root.sendJobInfo(e.threadJobs, e.threadJob);
      });
      root.sendModalResultLong(e.waitData, 0);
    } catch (t) {
      root.sendModalResultFailed(e.waitData);
      return;
    }
  },
  createToolWindow(e) {
    try {
      var t = createDOMElement(undefined, "div", "toolWindow");
      t.id = "toolWindow" + toolWindowId;
      t.persistenceId = e.guid;
      t.shadowDom = t.attachShadow({ mode: "open" });
      toolWindows[toolWindowId] = t;
      t.selfRemove = () => {
        document.body.removeChild(t);
      };
      let v = document.createElement("link");
      v.rel = "stylesheet";
      v.href = "styles.css";
      t.shadowDom.appendChild(v);
      {
        let e = document.createElement("link");
        e.rel = "stylesheet";
        e.href = "monaco-editor-0.35.1-pre-min\\vs\\editor\\editor.main.css";
        t.shadowDom.appendChild(e);
      }
      t.isResizable = true;
      var o = createDOMElement(undefined, "div", "toolWindowResizeLeft");
      t.shadowDom.appendChild(o);
      t.resizeLeftBar = o;
      o.onpointerdown = (e) => {
        var n = o;
        var i = parseInt(t.style.left);
        var r = t.clientWidth;
        n.setPointerCapture(e.pointerId);
        n.onpointermove = (o) => {
          var n = o.clientX - e.clientX;
          t.style.left = i + n + "px";
          t.style.width = r + -n + "px";
        };
        n.onpointerup = (o) => {
          n.onpointermove = undefined;
          n.onpointerup = undefined;
          n.releasePointerCapture(e.pointerId);
          var s = o.clientX - e.clientX;
          t.style.left = i + s + "px";
          t.style.width = r + -s + "px";
          saveFloatingToolWindowPosition(t);
        };
      };
      var n = createDOMElement(undefined, "div", "toolWindowResizeRight");
      t.shadowDom.appendChild(n);
      t.resizeRightBar = n;
      n.onpointerdown = (e) => {
        var o = n;
        var i = t.clientWidth;
        o.setPointerCapture(e.pointerId);
        o.onpointermove = (o) => {
          var n = o.clientX - e.clientX;
          t.style.width = i + n + "px";
        };
        o.onpointerup = (n) => {
          o.onpointermove = undefined;
          o.onpointerup = undefined;
          o.releasePointerCapture(e.pointerId);
          var r = n.clientX - e.clientX;
          t.style.width = i + r + "px";
          saveFloatingToolWindowPosition(t);
        };
      };
      var i = createDOMElement(undefined, "div", "toolWindowResizeTop");
      t.shadowDom.appendChild(i);
      t.resizeTopBar = i;
      i.onpointerdown = (e) => {
        var o = i;
        var n = parseInt(t.style.top);
        var r = t.clientHeight;
        o.setPointerCapture(e.pointerId);
        o.onpointermove = (o) => {
          var i = o.clientY - e.clientY;
          t.style.top = n + i + "px";
          t.style.height = r + -i + "px";
        };
        o.onpointerup = (i) => {
          o.onpointermove = undefined;
          o.onpointerup = undefined;
          o.releasePointerCapture(e.pointerId);
          var s = i.clientY - e.clientY;
          t.style.top = n + s + "px";
          t.style.height = r + -s + "px";
          saveFloatingToolWindowPosition(t);
        };
      };
      var r = createDOMElement(undefined, "div", "toolWindowResizeBottom");
      t.shadowDom.appendChild(r);
      t.resizeBottomBar = r;
      r.onpointerdown = (e) => {
        var o = r;
        var n = t.clientHeight;
        o.setPointerCapture(e.pointerId);
        o.onpointermove = (o) => {
          var i = o.clientY - e.clientY;
          t.style.height = n + i + "px";
        };
        o.onpointerup = (i) => {
          o.onpointermove = undefined;
          o.onpointerup = undefined;
          o.releasePointerCapture(e.pointerId);
          var r = i.clientY - e.clientY;
          t.style.height = n + r + "px";
          saveFloatingToolWindowPosition(t);
        };
      };
      var s = createDOMElement(
        undefined,
        "div",
        "toolWindowResizeCornerTopLeft"
      );
      t.shadowDom.appendChild(s);
      t.resizeCornerTopLeft = s;
      s.onpointerdown = (e) => {
        var o = s;
        var n = parseInt(t.style.left);
        var i = parseInt(t.style.top);
        var r = t.clientWidth;
        var a = t.clientHeight;
        o.setPointerCapture(e.pointerId);
        o.onpointermove = (o) => {
          var s = o.clientX - e.clientX;
          var l = o.clientY - e.clientY;
          t.style.left = n + s + "px";
          t.style.top = i + l + "px";
          t.style.width = r + -s + "px";
          t.style.height = a + -l + "px";
        };
        o.onpointerup = (s) => {
          o.onpointermove = undefined;
          o.onpointerup = undefined;
          o.releasePointerCapture(e.pointerId);
          var l = s.clientX - e.clientX;
          var d = s.clientY - e.clientY;
          t.style.left = n + l + "px";
          t.style.top = i + d + "px";
          t.style.width = r + -l + "px";
          t.style.height = a + -d + "px";
          saveFloatingToolWindowPosition(t);
        };
      };
      var a = createDOMElement(
        undefined,
        "div",
        "toolWindowResizeCornerTopRight"
      );
      t.shadowDom.appendChild(a);
      t.resizeCornerTopRight = a;
      a.onpointerdown = (e) => {
        var o = a;
        var n = parseInt(t.style.top);
        var i = t.clientWidth;
        var r = t.clientHeight;
        o.setPointerCapture(e.pointerId);
        o.onpointermove = (o) => {
          var s = o.clientX - e.clientX;
          var a = o.clientY - e.clientY;
          t.style.top = n + a + "px";
          t.style.width = i + s + "px";
          t.style.height = r + -a + "px";
        };
        o.onpointerup = (s) => {
          o.onpointermove = undefined;
          o.onpointerup = undefined;
          o.releasePointerCapture(e.pointerId);
          var a = s.clientX - e.clientX;
          var l = s.clientY - e.clientY;
          t.style.top = n + l + "px";
          t.style.width = i + a + "px";
          t.style.height = r + -l + "px";
          saveFloatingToolWindowPosition(t);
        };
      };
      var l = createDOMElement(
        undefined,
        "div",
        "toolWindowResizeCornerBottomRight"
      );
      t.shadowDom.appendChild(l);
      t.resizeCornerBottomRight = l;
      l.onpointerdown = (e) => {
        var o = l;
        var n = t.clientWidth;
        var i = t.clientHeight;
        o.setPointerCapture(e.pointerId);
        o.onpointermove = (o) => {
          var r = o.clientX - e.clientX;
          var s = o.clientY - e.clientY;
          t.style.width = n + r + "px";
          t.style.height = i + s + "px";
        };
        o.onpointerup = (r) => {
          o.onpointermove = undefined;
          o.onpointerup = undefined;
          o.releasePointerCapture(e.pointerId);
          var s = r.clientX - e.clientX;
          var a = r.clientY - e.clientY;
          t.style.width = n + s + "px";
          t.style.height = i + a + "px";
          saveFloatingToolWindowPosition(t);
        };
      };
      var d = createDOMElement(
        undefined,
        "div",
        "toolWindowResizeCornerBottomLeft"
      );
      t.shadowDom.appendChild(d);
      t.resizeCornerBottomLeft = d;
      d.onpointerdown = (e) => {
        var o = d;
        var n = parseInt(t.style.left);
        var i = t.clientWidth;
        var r = t.clientHeight;
        o.setPointerCapture(e.pointerId);
        o.onpointermove = (o) => {
          var s = o.clientX - e.clientX;
          var a = o.clientY - e.clientY;
          t.style.left = n + s + "px";
          t.style.width = i + -s + "px";
          t.style.height = r + a + "px";
        };
        o.onpointerup = (s) => {
          o.onpointermove = undefined;
          o.onpointerup = undefined;
          o.releasePointerCapture(e.pointerId);
          var a = s.clientX - e.clientX;
          var l = s.clientY - e.clientY;
          t.style.left = n + a + "px";
          t.style.width = i + -a + "px";
          t.style.height = r + l + "px";
          saveFloatingToolWindowPosition(t);
        };
      };
      t.eventInfoCacheId = 500;
      t.eventInfoCache = {};
      var c = createDOMElement(
        undefined,
        "div",
        "sectionHeader toolWindowTitleOuter"
      );
      t.shadowDom.appendChild(c);
      var u = createDOMElement(undefined, "div", "toolWindowTitle");
      c.appendChild(u);
      t.titleElement = u;
      var p = createDOMElement(undefined, "div", "toolWindowInnerFrame");
      t.shadowDom.appendChild(p);
      u.onpointerdown = (e) => {
        u.setPointerCapture(e.pointerId);
        var o = parseInt(t.style.left);
        var n = parseInt(t.style.top);
        u.onpointermove = (i) => {
          var r = i.clientX - e.clientX;
          var s = i.clientY - e.clientY;
          t.style.left = o + r + "px";
          t.style.top = n + s + "px";
        };
        u.onpointerup = (i) => {
          var r = i.clientX - e.clientX;
          var s = i.clientY - e.clientY;
          u.onmouseup = undefined;
          u.onpointermove = undefined;
          u.releasePointerCapture(e.pointerId);
          t.style.left = o + r + "px";
          t.style.top = n + s + "px";
          saveFloatingToolWindowPosition(t);
        };
      };
      var f = createDOMElement(undefined, "div", "toolWindowFrame");
      p.appendChild(f);
      var g = createDOMElement(undefined, "div", "toolWindowBody");
      f.appendChild(g);
      t.bodyElement = g;
      var m = document.createElement("div");
      m.className = "toolWindowTitleCloseBtn";
      m.innerHTML = "&nbsp;X&nbsp;";
      m.onpointerdown = (e) => {
        e.stopPropagation();
      };
      var h = toolWindowId;
      m.onmouseup = (e) => {
        this.toolWindowClose({ id: h });
      };
      m.title = "Close";
      c.appendChild(m);
      t.style.display = "none";
      if (floatingToolWindowsData[t.persistenceId]) {
        t.style.left = parseInt(floatingToolWindowsData[t.persistenceId].left);
        t.style.top = parseInt(floatingToolWindowsData[t.persistenceId].top);
        if (floatingToolWindowsData[t.persistenceId].width) {
          t.style.width = parseInt(
            floatingToolWindowsData[t.persistenceId].width
          );
        }
        if (floatingToolWindowsData[t.persistenceId].height) {
          t.style.height = parseInt(
            floatingToolWindowsData[t.persistenceId].height
          );
        }
      }
      document.body.insertBefore(t, document.body.firstChild);
      t.closeEventJob = () => {
        root.sendJobInfo(e.threadJobs, e.threadJob);
      };
    } catch (t) {
      root.sendModalResultFailed(e.waitData);
      return;
    }
    root.sendModalResultLong(e.waitData, toolWindowId++);
  },
  toolWindowClose(e) {
    try {
      var t = toolWindows[e.id];
      var o = t.closeEventJob;
      document.body.removeChild(t);
      delete toolWindows[e.id];
      if (o) o();
    } catch (t) {
      root.sendModalResultFailed(e.waitData);
      return;
    }
    root.sendModalResultLong(e.waitData, 0);
  },
  toolWindowApplyCss(e) {
    try {
      var t = toolWindows[e.id];
      let o = document.createElement("style");
      o.textContent = e.value;
      t.shadowDom.appendChild(o);
    } catch (t) {
      root.sendModalResultFailed(e.waitData);
      return;
    }
    root.sendModalResultLong(e.waitData, 0);
  },
  toolWindowGetTitle(e) {
    var t;
    try {
      t = toolWindows[e.id].titleElement.innerText;
    } catch (t) {
      root.sendModalResultFailed(e.waitData);
      return;
    }
    root.sendModalResultString(e.waitData, t);
  },
  toolWindowSetTitle(e) {
    try {
      toolWindows[e.id].titleElement.innerText = e.value;
    } catch (t) {
      root.sendModalResultFailed(e.waitData);
      return;
    }
    root.sendModalResultLong(e.waitData, 0);
  },
  toolWindowGetVisible(e) {
    var t;
    try {
      t = toolWindows[e.id].style.display == "none";
    } catch (t) {
      root.sendModalResultFailed(e.waitData);
      return;
    }
    root.sendModalResultLong(e.waitData, t ? false : true);
  },
  toolWindowSetVisible(e) {
    try {
      let t = toolWindows[e.id];
      t.style.display = e.value ? "block" : "none";
      if (e.value) {
        if (!floatingToolWindowsData[t.persistenceId]) {
          if (t.bodyElement.suggestedWidth) {
            t.style.width = t.bodyElement.suggestedWidth;
          }
          if (t.bodyElement.suggestedHeight) {
            t.style.height = t.bodyElement.suggestedHeight;
          }
        }
        if (!t.style.left) {
          if (t.clientWidth > t.parentNode.clientWidth) {
            if (t.parentNode.clientWidth > 300) {
              t.style.width = t.parentNode.clientWidth - 200 + "px";
            }
          }
          t.style.left = (t.parentNode.clientWidth - t.clientWidth) / 2 + "px";
        }
        if (!t.style.top) {
          if (t.clientHeight > t.parentNode.clientHeight) {
            if (t.parentNode.clientHeight > 300) {
              t.style.height = t.parentNode.clientHeight - 200 + "px";
            }
          }
          t.style.top = (t.parentNode.clientHeight - t.clientHeight) / 2 + "px";
        }
      }
    } catch (t) {
      root.sendModalResultFailed(e.waitData);
      return;
    }
    root.sendModalResultLong(e.waitData, 0);
  },
  toolWindowGetResizable(e) {
    var t;
    try {
      t = toolWindows[e.id].isResizable ? false : true;
    } catch (t) {
      root.sendModalResultFailed(e.waitData);
      return;
    }
    root.sendModalResultLong(e.waitData, t);
  },
  toolWindowSetResizable(e) {
    try {
      let t = toolWindows[e.id];
      t.isResizable = e.value ? true : false;
      t.resizeLeftBar.style.display = t.isResizable ? "block" : "none";
      t.resizeRightBar.style.display = t.isResizable ? "block" : "none";
      t.resizeTopBar.style.display = t.isResizable ? "block" : "none";
      t.resizeBottomBar.style.display = t.isResizable ? "block" : "none";
      t.resizeCornerBottomLeft.style.display = t.isResizable ? "block" : "none";
      t.resizeCornerBottomRight.style.display = t.isResizable
        ? "block"
        : "none";
      t.resizeCornerTopLeft.style.display = t.isResizable ? "block" : "none";
      t.resizeCornerTopRight.style.display = t.isResizable ? "block" : "none";
    } catch (t) {
      root.sendModalResultFailed(e.waitData);
      return;
    }
    root.sendModalResultLong(e.waitData, 0);
  },
  toolWindowElementAddChild(e) {
    try {
      var t = e.tagName;
      var o = toolWindows[e.id];
      var n = o.bodyElement;
      var i = e.element;
      i.findLast((e) => {
        n = n.querySelector(":scope #" + e);
      });
      if (
        e.tagName == "chartjs" ||
        e.tagName == "monaco" ||
        e.tagName == "listview" ||
        e.tagName == "virtuallistview"
      ) {
        t = "div";
      }
      var r = document.createElement(t);
      r.id = e.elementId;
      n.appendChild(r);
      if (e.tagName == "chartjs") {
        var s = document.createElement("canvas");
        r.appendChild(s);
        var a = new Chart(s, {
          type: "bar",
          data: { labels: [], datasets: [] },
          options: { scales: { x: {}, y: {} } },
        });
        a.data.createDataset = (e) => {
          a.data.datasets.push({});
          a.data.datasets[a.data.datasets.length - 1].label = e;
          a.data.datasets[a.data.datasets.length - 1].data = [];
        };
        r.chart = a;
        r.chart.data.pushAndWrap = (e, t, o) => {
          a.data.datasets[e].data.shift();
          a.data.datasets[e].data.push(t);
          if (o) a.update("none");
        };
      } else if (e.tagName == "monaco") {
        var l = monaco.editor.create(r, {
          minimap: { enabled: false },
          scrollbar: { vertical: "visible", horizontal: "visible" },
          wordWrap: "off",
        });
        l.setOption = (e, t) => {
          if (e == "language") {
            monaco.editor.setModelLanguage(l.getModel(), t);
          } else {
            var o = {};
            o[e] = t;
            l.updateOptions(o);
          }
        };
        r.editor = l;
        new ResizeObserver(() => {
          l.layout({ width: r.clientWidth, height: r.clientHeight });
        }).observe(r);
      } else if (e.tagName == "listview") {
        let e = createListView(r);
        r.style.position = "relative";
        r.listview = e;
        r.rootEventHandler = e;
      } else if (e.tagName == "virtuallistview") {
        let e = createVirtualListView(r);
        r.style.position = "relative";
        r.listview = e;
        r.rootEventHandler = e;
      }
    } catch (t) {
      root.sendModalResultFailed(e.waitData);
      return;
    }
    root.sendModalResultLong(e.waitData, 0);
  },
  toolWindowElementAddEventListener(e) {
    try {
      var t = toolWindows[e.id];
      var o = t.bodyElement;
      var n = e.element;
      n.findLast((e) => {
        o = o.querySelector(":scope #" + e);
      });
      if (o[e.event] === undefined && o["on" + e.event] === undefined) {
        this.toolWindowElementSetPropertyCallback(e);
        return;
      } else {
        o.addEventListener(e.event, (o) => {
          var n = t.eventInfoCacheId++;
          t.eventInfoCache[n] = copyEvent(o);
          if (e.data) t.eventInfoCache[n].data = e.data;
          root.sendJobInfo(e.threadJobs, e.threadJob, e.id, n);
        });
      }
    } catch (t) {
      root.sendModalResultFailed(e.waitData);
      return;
    }
    root.sendModalResultLong(e.waitData, 0);
  },
  toolWindowElementGetEventInfo(e) {
    var t;
    try {
      var o = toolWindows[e.id];
      var n = o.eventInfoCache[e.eventInfoId];
      t = n;
      var i = e.property;
      i.findLast((e) => {
        if (Array.isArray(e)) {
          if (Array.isArray(t)) {
            t = t[e];
          } else {
            t = t(...e);
            if (t === undefined) {
              t = null;
            }
          }
        } else {
          let o = t[e];
          if (o instanceof Function) {
            o = o.bind(t);
          }
          t = o;
        }
      });
      root.sendModalResultVariant(e.waitData, t);
    } catch (t) {
      root.sendModalResultFailed(e.waitData);
      return;
    }
  },
  toolWindowElementClearEventInfo(e) {
    try {
      var t = toolWindows[e.id];
      delete t.eventInfoCache[e.eventInfoId];
    } catch (e) {
      return;
    }
  },
  toolWindowElementRemove(e) {
    try {
      var t = toolWindows[e.id];
      var o = t.bodyElement;
      var n = e.element;
      n.findLast((e) => {
        o = o.querySelector(":scope #" + e);
      });
      if (o.isRootWidgetDiv) {
        activeAddinWidgets[e.id].selfRemove();
        delete toolWindows[e.id];
        delete activeAddinWidgets[e.id];
      } else {
        o.parentNode.removeChild(o);
      }
      root.sendModalResultLong(e.waitData, 0);
    } catch (t) {
      root.sendModalResultFailed(e.waitData);
      return;
    }
  },
  toolWindowElementGetProperty(e) {
    var t;
    try {
      var o = toolWindows[e.id];
      var n = o.bodyElement;
      var i = e.element;
      i.findLast((e) => {
        n = n.querySelector(":scope #" + e);
      });
      t = n;
      var r = e.property;
      var s = false;
      r.findLast((e) => {
        s = false;
        if (Array.isArray(e)) {
          if (Array.isArray(t)) {
            t = t[e];
          } else {
            t = t(...e);
            if (t === undefined) {
              t = null;
            }
          }
        } else {
          let n;
          if (e.substring(0, 1) === "#") {
            debugger;
            n = o.bodyElement.querySelector(":scope " + e);
            s = true;
          } else {
            n = t[e];
            if (n === undefined && i.length === 0) {
            }
            if (n instanceof Function) {
              n = n.bind(t);
            }
          }
          t = n;
        }
      });
      if (s) {
        t = t.value;
      }
      if (t instanceof Function) {
        t = t();
      }
      root.sendModalResultVariant(e.waitData, t);
    } catch (t) {
      root.sendModalResultFailed(e.waitData);
      return;
    }
  },
  toolWindowElementSetProperty(e) {
    try {
      var t = toolWindows[e.id];
      var o = t.bodyElement;
      var n = e.element;
      n.findLast((e) => {
        o = o.querySelector(":scope #" + e);
      });
      var i = o;
      var r = e.property;
      var s = r.shift();
      if (s.indexOf("on") == 0) {
      } else {
        r.findLast((e) => {
          if (Array.isArray(e)) {
            if (Array.isArray(i)) {
              debugger;
              i = i[e];
            } else {
              i = i(...e);
              if (i === undefined) {
                i = null;
              }
            }
          } else {
            let t = i[e];
            if (t instanceof Function) {
              t = t.bind(i);
            }
            i = t;
          }
        });
        i[s] = e.value;
      }
    } catch (t) {
      root.sendModalResultFailed(e.waitData);
      return;
    }
    root.sendModalResultLong(e.waitData, 0);
  },
  toolWindowElementSetPropertyCallback(e) {
    try {
      var t = toolWindows[e.id];
      var o = t.bodyElement;
      var n = e.element;
      n.findLast((e) => {
        o = o.querySelector(":scope #" + e);
      });
      var i = o;
      var r = e.property;
      if (r) {
        var s = r.shift();
        r.findLast((e) => {
          if (Array.isArray(e)) {
            if (Array.isArray(i)) {
              debugger;
              i = i[e];
            } else {
              i = i(...e);
              if (i === undefined) {
                i = null;
              }
            }
          } else {
            let t = i[e];
            if (t instanceof Function) {
              t = t.bind(i);
            }
            i = t;
          }
        });
      }
      i[e.event] = (o) => {
        var n = t.eventInfoCacheId++;
        t.eventInfoCache[n] = copyEvent(o);
        if (e.data) t.eventInfoCache[n].data = e.data;
        if (e.event.substring(0, 7) == "onAsync") {
          return new Promise((i) => {
            t.eventInfoCache[n].asyncArgument = o;
            t.eventInfoCache[n].setAsyncResult = i;
            root.sendJobInfo(e.threadJobs, e.threadJob, e.id, n);
          });
        } else {
          root.sendJobInfo(e.threadJobs, e.threadJob, e.id, n);
        }
      };
    } catch (t) {
      root.sendModalResultFailed(e.waitData);
      return;
    }
    root.sendModalResultLong(e.waitData, 0);
  },
  showNotification(e) {
    try {
      msgBox(e.message);
    } catch (e) {
      return;
    }
  },
  debugConsoleClear(e) {
    try {
      clearDebugConsole();
    } catch (e) {
      return;
    }
  },
  debugConsoleSetFocus(e) {
    try {
      focusDebugConsoleEntry();
    } catch (e) {
      return;
    }
  },
  getActiveEditorURI(e) {
    try {
      if (openEditors.selectedEditorNode === undefined) {
        root.sendModalResultString(e.waitData, "");
      } else {
        root.sendModalResultString(
          e.waitData,
          openEditors.editorContentId +
            "|" +
            openEditors.selectedEditorNode.type +
            "|twinbasic:" +
            openEditors.selectedEditorNode.fileNode.getFullPath()
        );
      }
    } catch (t) {
      root.sendModalResultFailed(e.waitData);
      return;
    }
  },
  openEditor(e) {
    try {
      var t = fs.tree.resolvePath(e.uri);
      debugger;
      if (t.isFolder) throw new Error("can't open editor for a folder");
      openEditors.openFile(
        t,
        false,
        false,
        false,
        e.lineNumber,
        e.columnNumber
      );
      root.sendModalResultLong(e.waitData, 1);
    } catch (t) {
      root.sendModalResultFailed(e.waitData);
      return;
    }
  },
  editorSetFocus(e) {
    try {
      if (e.editorContentId !== openEditors.editorContentId) {
        root.sendModalResultFailed(e.waitData);
        return;
      }
      editor.focus();
    } catch (e) {
      return;
    }
  },
  editorClose(e) {
    try {
      if (e.editorContentId !== openEditors.editorContentId) {
        root.sendModalResultFailed(e.waitData);
        return;
      }
      openEditors.closeFile(openEditors.selectedEditorNode);
    } catch (e) {
      return;
    }
  },
  editorSave(e) {
    try {
      if (e.editorContentId !== openEditors.editorContentId) {
        root.sendModalResultFailed(e.waitData);
        return;
      }
      openEditors.save(openEditors.selectedEditorNode);
    } catch (e) {
      return;
    }
  },
  editorIsDirty(e) {
    var t;
    try {
      if (e.editorContentId !== openEditors.editorContentId) {
        root.sendModalResultFailed(e.waitData);
        return;
      }
      t = openEditors.isDirtyEditor(openEditors.selectedEditorNode);
    } catch (t) {
      root.sendModalResultFailed(e.waitData);
      return;
    }
    root.sendModalResultLong(e.waitData, t ? 1 : 0);
  },
  editorGetSelectionInfo(e) {
    try {
      if (e.editorContentId !== openEditors.editorContentId) {
        root.sendModalResultFailed(e.waitData);
        return;
      }
      const t = editor.getSelection();
      if (!t) {
        root.sendModalResultString(e.waitData, "");
        return;
      }
      root.sendModalResultString(
        e.waitData,
        t.startLineNumber +
          "|" +
          t.startColumn +
          "|" +
          t.endLineNumber +
          "|" +
          t.endColumn
      );
    } catch (t) {
      root.sendModalResultFailed(e.waitData);
      return;
    }
  },
  editorSetSelectionInfo(e) {
    try {
      if (e.editorContentId !== openEditors.editorContentId) {
        root.sendModalResultFailed(e.waitData);
        return;
      }
      editor.setSelection({
        startLineNumber: e.startLine,
        startColumn: e.startColumn,
        endLineNumber: e.endLine,
        endColumn: e.endColumn,
      });
      root.sendModalResultLong(e.waitData, 1);
    } catch (t) {
      root.sendModalResultFailed(e.waitData);
      return;
    }
  },
  editorRevealRange(e) {
    try {
      if (e.editorContentId !== openEditors.editorContentId) {
        root.sendModalResultFailed(e.waitData);
        return;
      }
      var t = {
        startLineNumber: e.startLine,
        startColumn: e.startColumn,
        endLineNumber: e.endLine,
        endColumn: e.endColumn,
      };
      var o = e.smoothScroll ? 0 : 1;
      if (e.areaEnum == 1) {
        editor.revealRangeAtTop(t, o);
      } else if (e.areaEnum == 2) {
        editor.revealRangeInCenter(t, o);
      } else if (e.areaEnum == 3) {
        editor.revealRangeInCenterIfOutsideViewport(t, o);
      } else if (e.areaEnum == 4) {
        editor.revealRangeNearTop(t, o);
      } else if (e.areaEnum == 5) {
        editor.revealRangeNearTopIfOutsideViewport(t, o);
      } else {
        editor.revealRange(t, o);
      }
      root.sendModalResultLong(e.waitData, 1);
    } catch (t) {
      root.sendModalResultFailed(e.waitData);
      return;
    }
  },
  editorGetSelectedText(e) {
    var t;
    try {
      if (e.editorContentId !== openEditors.editorContentId) {
        root.sendModalResultFailed(e.waitData);
        return;
      }
      const i = editor.getSelection();
      if (!i || i.isEmpty()) {
        root.sendModalResultString(e.waitData, "");
        return;
      }
      var o = parseInt(liveIDEOptions["tabSize"]);
      var n = " ".repeat(o);
      debugOutputLineCopyPaste("tabSpacesCount: " + o);
      debugOutputLineCopyPaste("tabSpacesString: '" + n + "'");
      let r = editor.getModel();
      t = r?.getValueInRange(i);
      t = t.replaceAll("\t", n);
    } catch (t) {
      root.sendModalResultFailed(e.waitData);
      return;
    }
    root.sendModalResultString(e.waitData, t);
  },
  editorSetSelectedText(e) {
    try {
      if (e.editorContentId !== openEditors.editorContentId) {
        root.sendModalResultFailed(e.waitData);
        return;
      }
      const o = editor.getSelection();
      if (!o) {
        var t = editor.getPosition();
        o = {
          startColumn: t.column,
          startLineNumber: t.lineNumber,
          endColumn: t.column,
          endLineNumber: t.lineNumber,
        };
      }
      editor.executeEdits("clipboard", [
        { range: o, text: e.value, forceMoveMarkers: true },
      ]);
    } catch (t) {
      root.sendModalResultFailed(e.waitData);
      return;
    }
    root.sendModalResultLong(e.waitData, 0);
  },
  editorGetText(e) {
    try {
      if (e.editorContentId !== openEditors.editorContentId) {
        root.sendModalResultFailed(e.waitData);
        return;
      }
      let o = editor.getModel();
      var t = o?.getValue();
    } catch (t) {
      root.sendModalResultFailed(e.waitData);
      return;
    }
    root.sendModalResultString(e.waitData, t);
  },
  editorSetText(e) {
    try {
      if (e.editorContentId !== openEditors.editorContentId) {
        root.sendModalResultFailed(e.waitData);
        return;
      }
      let t = editor.getModel();
      editor.executeEdits("clipboard", [
        { range: t.getFullModelRange(), text: e.value, forceMoveMarkers: true },
      ]);
    } catch (t) {
      root.sendModalResultFailed(e.waitData);
      return;
    }
    root.sendModalResultLong(e.waitData, 0);
  },
  addMonacoWidget(e) {
    try {
      if (e.editorContentId !== openEditors.editorContentId) {
        root.sendModalResultFailed(e.waitData);
        return;
      }
      let t = createDOMElement(undefined, "div", "");
      t.shadowDom = t.attachShadow({ mode: "open" });
      let o = createDOMElement(t.shadowDom, "div", "");
      toolWindows[toolWindowId] = t;
      activeAddinWidgets[toolWindowId] = t;
      let n = toolWindowId;
      o.innerHTML = e.html;
      t.bodyElement = o;
      t.eventInfoCacheId = 500;
      t.eventInfoCache = {};
      t.shadowDom.rootEventHandler = o;
      o.isRootWidgetDiv = true;
      if (e.css && e.css.length > 0) {
        let o = document.createElement("style");
        o.textContent = e.css;
        t.shadowDom.appendChild(o);
      }
      t.id = "addinWidgetId" + n;
      t.overlayWidget = {
        getId: () => "overlay.zone.widget" + n,
        getDomNode: () => t,
        getPosition: e.columnNumber
          ? function () {
              return {
                position: {
                  lineNumber: t.currentLineNumber,
                  column: t.currentColumnNumber,
                },
                preference: [
                  monaco.editor.ContentWidgetPositionPreference.ABOVE,
                  monaco.editor.ContentWidgetPositionPreference.BELOW,
                ],
              };
            }
          : () => null,
      };
      t.currentLineNumber = e.lineNumber;
      t.currentColumnNumber = e.columnNumber;
      if (e.columnNumber) {
        t.wholeLine = false;
        t.trackerDecoration = editor.deltaDecorations(
          [],
          [
            {
              range: new monaco.Range(
                e.lineNumber,
                e.columnNumber,
                e.lineNumber,
                e.columnNumber
              ),
              options: { glyphMarginClassName: "", stickiness: 1 },
            },
          ]
        );
        editor.addContentWidget(t.overlayWidget);
        t.selfRemove = () => {
          editor.removeContentWidget(t.overlayWidget);
          editor.deltaDecorations(t.trackerDecoration, []);
        };
      } else {
        t.wholeLine = true;
        t.trackerDecoration = editor.deltaDecorations(
          [],
          [
            {
              range: new monaco.Range(
                e.lineNumber,
                9999999999,
                e.lineNumber,
                9999999999
              ),
              options: { glyphMarginClassName: "", stickiness: 1 },
            },
          ]
        );
        editor.addOverlayWidget(t.overlayWidget);
        t.selfRemove = () => {
          editor.removeOverlayWidget(t.overlayWidget);
          editor.deltaDecorations(t.trackerDecoration, []);
          editor.changeViewZones(function (e) {
            e.removeZone(t.viewZoneId);
          });
        };
        let o = document.createElement("div");
        o.id = "zoneId" + toolWindowId;
        editor.changeViewZones(function (n) {
          t.myZone = {
            afterLineNumber: e.lineNumber,
            get heightInPx() {
              const e = editor.getLayoutInfo();
              t.style.width = e.width - e.verticalScrollbarWidth + "px";
              return t.offsetHeight;
            },
            domNode: o,
            onDomNodeTop: (e) => {
              t.style.top = e + "px";
              const o = editor.getLayoutInfo();
              t.style.width = o.width - o.verticalScrollbarWidth + "px";
            },
            onComputedHeight: (e) => {
              t.style.height = e + "px";
              const o = editor.getLayoutInfo();
              t.style.width = o.width - o.verticalScrollbarWidth + "px";
            },
          };
          t.viewZoneId = n.addZone(t.myZone);
        });
      }
      root.sendModalResultLong(e.waitData, toolWindowId++);
    } catch (t) {
      root.sendModalResultFailed(e.waitData);
      return;
    }
  },
  editorExecuteMonacoCommand(e) {
    try {
      if (e.editorContentId !== openEditors.editorContentId) {
        root.sendModalResultFailed(e.waitData);
        return;
      }
      if (e.commandArgs.length > 0) {
        editor.trigger("", e.command, e.commandArgs);
      } else {
        editor.trigger("", e.command);
      }
    } catch (e) {
      return;
    }
  },
  currentProjectSave(e) {
    try {
      saveProject();
    } catch (t) {
      root.sendModalResultFailed(e.waitData);
      return;
    }
    root.sendModalResultLong(e.waitData, 0);
  },
  currentProjectClose(e) {
    try {
      closeProjectSafely();
    } catch (t) {
      root.sendModalResultFailed(e.waitData);
      return;
    }
    root.sendModalResultLong(e.waitData, 0);
  },
  currentProjectBuild(e) {
    try {
      buildIcon.onclick();
    } catch (t) {
      root.sendModalResultFailed(e.waitData);
      return;
    }
    root.sendModalResultLong(e.waitData, 0);
  },
  currentProjectClean(e) {
    try {
      trashIcon.onclick();
    } catch (t) {
      root.sendModalResultFailed(e.waitData);
      return;
    }
    root.sendModalResultLong(e.waitData, 0);
  },
};
function showHKLMwarning(e) {
  var t = createDOMElement(undefined, "div", "simpleMsgBox", "");
  t.innerHTML =
    "WARNING: This project registers itself to the HKEY_LOCAL_MACHINE<br/>registry hive which requires ADMIN permissions.<br><br>The twinBASIC IDE is not currently running elevated, and so <br/>the registration of the DLL will fail during the build process.<br/><br/>For the build to be successful, please restart the twinBASIC IDE <br/>using the 'Run As Administrator' Windows option.";
  showModalDialog(t, [
    {
      caption: "CONTINUE ANYWAY",
      onclick: () => {
        hideModalDialog();
        e();
      },
      isDefaultCancelAction: true,
    },
  ]);
}
function responseCodeErrorToString(e) {
  switch (e) {
    case responseCodeError_Generic:
      return "ERROR_GENERIC";
    case responseCodeError_FileNotFound:
      return "ERROR_FILE_NOT_FOUND";
    case responseCodeError_BadFileFormat:
      return "ERROR_BAD_FILE_FORMAT";
    default:
      return "ERROR_UNKNOWN";
  }
}
async function createCompilerInstance(e) {
  var t = buildConfigSelector.value;
  var o = t === "nocompile";
  if (o) t = "win32";
  var n = await hostAppObject.CreateCompilerInstance(
    t,
    o,
    liveIDEOptions["ideDataExecutionPrevention"],
    liveIDEOptions["ideLargeAddressAware"]
  );
  if (n !== 0) {
    if (isDebugMode) debugOutputLine("Root Compiler Port: " + n);
    compilerPassKey = await hostAppObject.GetCompilerPassKey("ignore");
    e(n);
  } else {
    hideModalProgressIndicator();
  }
}
async function getIDECommandLineArgs(e) {
  var t = await hostAppObject.GetCmdLine("ignore");
  e(t);
}
function syncTitleBar() {
  if (rootMenuText === undefined) return;
  rootMenuText.classList.remove("hide");
  var e = " ";
  var t = projectFilePath
    ? projectFilePath.split("\\").pop()
    : "未保存的项目";
  var o = projectFilePath ? projectFilePath : "未保存的项目";
  if (projectIsLoaded)
    e =
      (projectIsDirty ? "• " : "") + t + " - twinBASIC (" + tbVersionInfo + ")";
  rootMenuText.innerText = e;
  rootMenuTitleFull.innerText = e;
  rootMenuText.title = o;
  rootMenuTitleFull.title = o;
  var n = rootMenuTextOuter.offsetLeft;
  var i = rootMenuText.offsetWidth / 2;
  var r = document.body.offsetWidth / 2;
  var s = r - n;
  if (i >= s) {
    rootMenuText.classList.remove("invisible");
    rootMenuTitleFull.classList.add("hide");
  } else {
    rootMenuText.classList.add("invisible");
    rootMenuTitleFull.classList.remove("hide");
  }
  hostAppObject.SetWindowTitle(
    (projectIsDirty ? "• " : "") + t.split("\\").pop()
  );
}
var root = undefined;
class _RootConnection {
  constructor() {
    this.liveBackupRequestId = 0;
    this.liveBackupResponses = {};
  }
  ensureWebsocketConnected(e) {
    if (!this.webSocket) {
      createCompilerInstance((t) => {
        this.callbackOnWebsocketConnected = e;
        this.webSocket = new webSocket(
          "ws://localhost:" + t.toString() + "/" + compilerPassKey + "/root",
          this
        );
      });
    } else {
      e();
    }
  }
  onConnected() {
    var e = "";
    hostAppObject_packagesList.forEach((t) => {
      if (t && t.length > 0) e += t + "?";
    });
    lastCompilerStart_ideDataExecutionPrevention =
      liveIDEOptions["ideDataExecutionPrevention"];
    lastCompilerStart_ideLargeAddressAware =
      liveIDEOptions["ideLargeAddressAware"];
    lastCompilerStart_showAdvancedHoverInfo =
      liveIDEOptions["showAdvancedHoverInfo"];
    lastCompilerStart_showHiddenMembers = liveIDEOptions["showHiddenMembers"];
    lastCompilerStart_useHandlesImplementsSyntax =
      liveIDEOptions["useHandlesImplementsSyntax"];
    lastCompilerStart_showDebuggerMemUsage =
      liveIDEOptions["showDebuggerMemUsage"];
    this.webSocket.request1a(
      RequestPreInitialize,
      currentDPI * 96,
      "",
      (t, o) => {
        this.webSocket.request1a(
          RequestInitialize,
          (liveIDEOptions["showAdvancedHoverInfo"] ? 1 : 0) +
            (liveIDEOptions["showHiddenMembers"] ? 2 : 0) +
            (liveIDEOptions["useHandlesImplementsSyntax"] ? 4 : 0) +
            (liveIDEOptions["showDebuggerMemUsage"] ? 8 : 0),
          e,
          (e, t) => {
            if (debugMode) {
              this.webSocket.request1a(
                RequestSetDebugMode,
                debugMode,
                "",
                (e, t) => {}
              );
            }
            var o = new Int32Array(t, 0, 5);
            this.fileSystemPort = o[0];
            this.debuggerPort = o[1];
            this.lspPort = o[2];
            this.formImageServerPort = o[3];
            this.liveBackupPort = o[4];
            this.serverID = new TextDecoder().decode(t.slice(20));
            if (this.callbackOnWebsocketConnected) {
              this.callbackOnWebsocketConnected();
              delete this.callbackOnWebsocketConnected;
            }
          }
        );
      }
    );
  }
  onNotification(e, t) {
    if (e === ReverseRequestAddInRequest) {
      var o = new DataView(t);
      let e = new TextDecoder().decode(o);
      let n = JSON.parse(e);
      addInEvents[n.method](n.params);
    } else if (e === ReverseRequestGetPackageFileData) {
      var n = new TextDecoder().decode(t);
      GetPackageFileData(n, (e) => {
        this.webSocket.request2(
          RequestProvidePackageFileData,
          n,
          e,
          (e, t) => {}
        );
      });
    } else if (e === ReverseRequestSaveInMemoryProject) {
      var o = new DataView(t);
      var i = o.getInt32(0, true);
      msgBox(
        "此项目尚未保存。  现在保存吗？",
        ["YES", "NO"],
        (e) => {
          if (e == "YES") {
            saveProjectAs();
          }
        }
      );
    } else if (e === ReverseRequestProjectIsDirtyState) {
      var o = new DataView(t);
      var r = o.getInt32(0, true);
      projectIsDirty = r ? true : false;
      syncTitleBar();
      if (!projectIsDirty) {
        this.sendLiveBackupWorkerMessage("cachedIsStale", []);
      }
    } else if (e === ReverseRequestSettingsFileChanged) {
      this.onSaveFileComplete(() => {
        restartCompilerSafely();
      });
    } else if (e === ReverseRequestIPC) {
      var s = new TextDecoder().decode(t);
      debugSocket.request("x", { x: s });
    } else if (e === ReverseRequestKeyValidationResult) {
      var o = new DataView(t);
      var a = o.getInt32(0, true);
      var l = new DataView(t, 4);
      var d = new TextDecoder().decode(l);
      if (d !== licenceKey) {
        hostAppObject.SaveIDESetting("LicenceKey", d);
        licenceKey = d;
        if (a != 0) {
          msgBox("Licence key applied successfully.  Thanks for your support.");
        } else {
          msgBox("Invalid licence key.  Please try again.");
        }
      }
      if (a === 2) {
        compilerLicence.innerText = "PROFESSIONAL EDITION";
        compilerLicenceOuter.classList.add("servicesOK");
        compilerLicenceOuter.classList.remove("servicesPARTIAL");
        compilerLicenceOuter.title = compilerLicence.innerText;
      } else if (a == 1) {
        compilerLicence.innerText = "ULTIMATE EDITION";
        compilerLicenceOuter.classList.add("servicesOK");
        compilerLicenceOuter.classList.remove("servicesPARTIAL");
        compilerLicenceOuter.title = compilerLicence.innerText;
      } else {
        compilerLicence.innerText = "COMMUNITY EDITION";
        compilerLicenceOuter.classList.add("servicesPARTIAL");
        compilerLicenceOuter.classList.remove("servicesOK");
        compilerLicenceOuter.title = compilerLicence.innerText;
      }
    } else if (e === ReverseRequestProcessStarted) {
      var o = new DataView(t);
      var c = o.getInt32(0, true);
      var u = createDOMElement(
        runningProcessesContainer,
        "div",
        "runningProcessOuter"
      );
      var p = createDOMElement(
        u,
        "div",
        "runningProcess",
        "PROCESS " + c.toString() + ": RUNNING"
      );
      runningProcessesContainer.appendChild(u);
      u.processId = c;
      u.onclick = () => {
        showContextMenu(
          undefined,
          u.offsetLeft,
          u.offsetTop,
          [
            {
              name: "Terminate",
              action: () => {
                this.webSocket.request1(
                  RequestTerminateProcess,
                  intToUint8Array(c)
                );
              },
            },
            {
              name: "Bring To Front",
              action: () => {
                this.webSocket.request1(
                  RequestBringProcessToFront,
                  intToUint8Array(c)
                );
              },
            },
          ],
          u.offsetWidth,
          true
        );
      };
    } else if (e === ReverseRequestProcessEnded) {
      var o = new DataView(t);
      var c = o.getInt32(0, true);
      var f = Array.prototype.slice.call(runningProcessesContainer.childNodes);
      f.forEach((e) => {
        if (e.processId === c) {
          runningProcessesContainer.removeChild(e);
        }
      });
    } else if (e === ReverseRequestMsgBox) {
      let e = new DataView(t);
      let o = new TextDecoder().decode(e);
      msgBox(o);
    } else if (e === ReverseRequestSaveFailed) {
      var o = new DataView(t);
      var g = o.getInt32(0, true);
      var m = o.getInt32(4, true);
      var h = new DataView(t, 8, m);
      var v = new TextDecoder().decode(h);
      v = v.trim();
      var y = createDOMElement(
        undefined,
        "div",
        "simpleMsgBox",
        "保存项目失败。  如果需要，检查项目文件路径并调整。"
      );
      var b = createDOMElement(y, "input", "dialogFilePathInput", "");
      var C = createDOMElement(y, "div", "", "Error " + g + " [" + v + "]");
      b.value = projectFilePath;
      showModalDialog(y, [
        {
          caption: "Try Again",
          onclick: () => {
            hideModalDialog();
            var e = b.value;
            hostAppObject.AddRecentsList(e);
            projectFilePath = e;
            syncTitleBar();
            this.webSocket.request1a(RequestSaveFailedResponse, 2, e);
          },
        },
        {
          caption: "取消",
          onclick: () => {
            hideModalDialog();
            this.webSocket.request1a(RequestSaveFailedResponse, 1, "");
          },
          isDefaultCancelAction: true,
        },
      ]);
    } else if (e === ReverseRequestProgressLogSynchronous) {
      let e = new DataView(t);
      let o = new TextDecoder().decode(e);
      setModalProgressLog(o);
      this.webSocket.request0(
        RequestProgressLogSynchronousResponse,
        (e, t) => {}
      );
    } else if (e === ReverseRequestReferenceProblem) {
      let e = new DataView(t);
      let o = new TextDecoder().decode(e);
      var E = o.split("|||");
      var I = (E.length - 1) / 3;
      var D =
        "WARNING: There was a problem loading " +
        I +
        " reference" +
        (I > 1 ? "s" : "") +
        ":<br/><br/>";
      var S = 0;
      while (S < I) {
        var P = E[S * 3];
        var w = E[S * 3 + 1];
        var T = E[S * 3 + 2];
        problemReferences.push({
          problemRefVerMajor: P,
          problemRefVerMinor: w,
          problemRefDescription: T,
        });
        D += " &nbsp; &nbsp; &nbsp; " + T + " (v" + P + "." + w + ")";
        D += "<br/>";
        S++;
      }
      setTimeout(() => showReferences(), 2e3);
    } else if (e === ReverseRequestMassageSettings) {
      var o = new DataView(t);
      var L = o.getInt32(0, true);
      var l = new DataView(t, 4, t.byteLength - 4);
      let e = new TextDecoder().decode(l);
      let n = JSON.parse(e);
      if (g_ShowNewProjectOptions) {
        showNewProjectOptions(n, L, (e) => {
          var t = 0;
          if (e["project.name"] !== undefined) {
            n["project.name"] = e["project.name"];
            if (!g_IsLoadingVBP) {
              n["project.description"] = e["project.name"];
              n["project.appTitle"] = e["project.name"];
            }
          }
          if (e["project.optionExplicit"] !== undefined)
            n["project.optionExplicit"] = e["project.optionExplicit"];
          if (e["project.forceDpiAwarenessAtStartup"] !== undefined)
            n["project.forceDpiAwarenessAtStartup"] =
              e["project.forceDpiAwarenessAtStartup"];
          if (e["project.dllRegisterLocalMachine"] !== undefined)
            n["project.dllRegisterLocalMachine"] =
              e["project.dllRegisterLocalMachine"];
          if (e["misc.visualStyles"]) {
            t = 1;
          }
          if (e["misc.winNativeCommonCtls"]) {
            var o = { id: "{D63CB78D-9F5B-42FE-B94C-A545F2B2BFC3}" };
            n["project.references"].push(o);
          }
          let i = () => {
            this.webSocket.request1a(
              RequestProvideMassagedSettingsResult,
              t,
              JSON.stringify(n, null, "\t"),
              (e, t) => {}
            );
          };
          g_IsLoadingVBP = false;
          if (n["project.dllRegisterLocalMachine"] && !g_Elevated) {
            showHKLMwarning(i);
          } else {
            i();
          }
        });
      } else {
        let e = () => {
          this.webSocket.request1a(
            RequestProvideMassagedSettingsResult,
            0,
            "",
            (e, t) => {}
          );
        };
        if (n["project.dllRegisterLocalMachine"] && !g_Elevated) {
          showHKLMwarning(e);
        } else {
          e();
        }
      }
      g_ShowNewProjectOptions = false;
    } else {
      alert("根对象通知: " + e + "; " + t.toString());
    }
  }
  saveProjectAs(e, t) {
    saveProjectMetaState(() => {
      this.webSocket.request1(RequestSaveProjectAs, e, (o, n) => {
        hostAppObject.AddRecentsList(e);
        projectFilePath = e;
        syncTitleBar();
        if (t) t();
      });
    });
  }
  setCurrentProjectInfo(e) {
    g_CurrentProjectMajorVersion = parseInt(e[0]);
    g_CurrentProjectMinorVersion = parseInt(e[1]);
    g_CurrentProjectRevisionVersion = parseInt(e[2]);
    g_CurrentProjectBuildVersion = parseInt(e[3]);
    g_CurrentProjectIsPackage = parseInt(e[4]) != 0;
    g_CurrentProjectName = e[5];
    g_CurrentProjectDescription = e[6];
    g_CurrentProjectLicence = e[7];
    g_CurrentProjectVisibility = e[8];
    syncPackageManagerPanel();
  }
  loadProject(e) {
    showModalProgressIndicator();
    hostAppObject.AddRecentsList(e);
    this.ensureWebsocketConnected(() => {
      this.webSocket.request1(RequestLoadProject, e, (t, o) => {
        if (t == 0) {
          let t = new DataView(o);
          let i = new TextDecoder().decode(t);
          var n = i.split("|||");
          this.setCurrentProjectInfo(n);
          projectFilePath = e;
          projectIsDirty = false;
          this.allProjectsLoaded();
        } else {
          hideModalProgressIndicator();
          closeProjectNow(() => {});
          var i = createDOMElement(
            undefined,
            "div",
            "simpleMsgBox simpleMsgBoxError",
            "Failed to load the project (error code " +
              responseCodeErrorToString(t) +
              ")\n\n" +
              e +
              "\n\nDo you want to remove it from the list of recently opened projects?"
          );
          showModalDialog(i, [
            {
              caption: "Remove it",
              onclick: () => {
                hostAppObject.RemoveRecentsList(e);
                hideModalDialog();
              },
            },
            {
              caption: "Keep it",
              onclick: hideModalDialog,
              isDefaultCancelAction: true,
            },
          ]);
        }
      });
    });
  }
  exportProject(e, t) {
    this.ensureWebsocketConnected(() => {
      this.webSocket.request1a(RequestExportProject, t, e, (e, t) => {
        if (e == 0) {
        } else {
          msgBox(
            "错误：exportProject失败。  错误代码 " +
              responseCodeErrorToString(e)
          );
        }
      });
    });
  }
  exportFile(e, t, o) {
    this.ensureWebsocketConnected(() => {
      this.webSocket.request2a(RequestExportFile, o, 0, e, t, (e, t) => {
        if (e == 0) {
        } else {
          msgBox(
            "错误：exportFile失败。  错误代码 " +
              responseCodeErrorToString(e)
          );
        }
      });
    });
  }
  loadProjectVBP(e) {
    g_ShowNewProjectOptions = true;
    g_IsLoadingVBP = true;
    showModalProgressIndicator(true);
    this.ensureWebsocketConnected(() => {
      this.webSocket.request1(RequestImportProjectVBP, e, (e, t) => {
        if (e == 0) {
          let e = new DataView(t);
          let n = new TextDecoder().decode(e);
          var o = n.split("|||");
          this.setCurrentProjectInfo(o);
          projectFilePath = undefined;
          projectIsDirty = true;
          this.allProjectsLoaded();
        } else {
          msgBox(
            "错误：LoadProject失败。  错误代码 " +
              responseCodeErrorToString(e)
          );
        }
      });
    });
  }
  loadProjectFromFolder(e) {
    showModalProgressIndicator();
    this.ensureWebsocketConnected(() => {
      this.webSocket.request1(RequestImportProjectFolder, e, (e, t) => {
        if (e == 0) {
          if (t.byteLength > 0) {
            let e = new DataView(t);
            let n = new TextDecoder().decode(e);
            var o = n.split("|||");
            this.setCurrentProjectInfo(o);
            projectFilePath = undefined;
            projectIsDirty = true;
            this.allProjectsLoaded();
          } else {
            msgBox(
              "错误：从文件夹加载项目失败。  检查文件夹是否有效。"
            );
            hideModalProgressIndicator();
          }
        } else {
          msgBox(
            "错误：LoadProject失败。  错误代码 " +
              responseCodeErrorToString(e)
          );
          hideModalProgressIndicator();
        }
      });
    });
  }
  loadProjectFromMemory(e, t, o) {
    showModalProgressIndicator();
    this.ensureWebsocketConnected(() => {
      this.webSocket.request2(
        RequestLoadProjectFromMemory,
        e,
        o ? o : t ? t : "",
        (e, o) => {
          let n = new DataView(o);
          let i = new TextDecoder().decode(n);
          var r = i.split("|||");
          this.setCurrentProjectInfo(r);
          if (!t) {
            projectFilePath = undefined;
            projectIsDirty = true;
          } else {
            projectFilePath = t;
            projectIsDirty = true;
          }
          this.allProjectsLoaded();
        }
      );
    });
  }
  allProjectsLoaded() {
    latestFileSystemInMemory = undefined;
    projectIsLoaded = true;
    syncTitleBar();
    if (liveIDEOptions["showDebuggerMemUsage"]) {
      statusMemUsageDiv.classList.remove("hide");
    }
    this.webSocket.request0(RequestAllProjectsLoaded, (e, t) => {
      let o = new DataView(t);
      projectBuildPath = new TextDecoder().decode(o);
      doLayoutChanges(() => {
        fs.connect(this.fileSystemPort, () => {
          lspSocket.connect(this.lspPort, () => {
            debugSocket.connect(this.debuggerPort, () => {
              if (!shiftKeyDown) {
                this.webSocket.request0(RequestLoadAddins, (e, t) => {
                  this.createLiveBackupWebworker();
                  loadProjectMetaState();
                });
              } else {
                debugOutputLine(
                  "[IDE] SHIFT KEY DETECTED: DISABLED LOADING OF ADDINS"
                );
                this.createLiveBackupWebworker();
                loadProjectMetaState();
              }
            });
          });
        });
      });
    });
  }
  multiUpdateStart(e) {
    this.webSocket.request0(RequestMultiUpdateStart, (t, o) => {
      e();
    });
  }
  multiUpdateEnd(e) {
    this.webSocket.request0(RequestMultiUpdateEnd, (t, o) => {
      e();
    });
  }
  createLiveBackupWebworker() {
    this.liveBackupWorker = new Worker("liveBackupWorker.js");
    this.liveBackupWorker.onmessage = (e) => {
      var t = this.liveBackupResponses[e.data[0]];
      if (t) {
        t(e);
        delete this.liveBackupResponses[e.data[0]];
      }
    };
    this.sendLiveBackupWorkerMessage("start", [
      this.liveBackupPort,
      compilerPassKey,
    ]);
  }
  sendLiveBackupWorkerMessage(e, t, o) {
    this.liveBackupRequestId++;
    if (o) this.liveBackupResponses[this.liveBackupRequestId] = o;
    this.liveBackupWorker.postMessage([this.liveBackupRequestId, e, ...t]);
  }
  forceTerminate() {
    if (this.webSocket) {
      this.webSocket.request0(RequestShutdown, (e, t) => {});
      try {
        this.webSocket.close();
      } catch (e) {}
    } else {
      projectClosed();
    }
  }
  notifyChangedActiveEditor(e, t, o, n) {
    if (this.webSocket) {
      this.webSocket.request2a(
        RequestNotifyChangedActiveEditor,
        e,
        n,
        t,
        o,
        (e, t) => {}
      );
    }
  }
  sendModalResultFailed(e) {
    if (e) {
      this.webSocket.request1a(
        RequestNotifyModalResultFailed,
        0,
        e + "",
        (e, t) => {}
      );
    }
  }
  sendModalResultLong(e, t) {
    if (e) {
      this.webSocket.request1a(
        RequestNotifyModalResult,
        t,
        e + "",
        (e, t) => {}
      );
    }
  }
  sendModalResultString(e, t) {
    if (e) {
      this.webSocket.request2(
        RequestNotifyModalResultString,
        t,
        e + "",
        (e, t) => {}
      );
    }
  }
  sendModalResultVariant(e, t) {
    if (e) {
      this.webSocket.request2(
        RequestNotifyModalResultVariant,
        JSON.stringify(t),
        e + "",
        (e, t) => {}
      );
    }
  }
  sendJobInfo(e, t, o, n) {
    this.webSocket.request2a(RequestQueueJob, o, n, e, t, (e, t) => {});
  }
  getAddinsList(e) {
    this.webSocket.request0(RequestAddinsStateList, (t, o) => {
      let n = new DataView(o);
      var i = new TextDecoder().decode(n);
      e(JSON.parse(i));
    });
  }
  onSaveFileComplete(e, t) {
    if (!this.webSocket) {
      e();
      return;
    }
    this.webSocket.request0(RequestWaitForSaveProjectCompletion, (o, n) => {
      var i = new Int8Array(n, 0, 1);
      if (i[0] == 1) {
        saveProjectMetaState(() => {
          debugger;
          e();
        });
      } else {
        msgBox("保存项目失败。");
        t();
      }
    });
  }
  Shell(e, t) {
    if (t) {
      this.webSocket.request1(RequestShellMuted, e, (e, t) => {});
    } else {
      allowCompilerProcessToSetForegroundWIndow(() => {
        this.webSocket.request1(RequestShell, e, (e, t) => {});
      });
    }
  }
}
function initRootConnection() {
  root = new _RootConnection();
}
var currentDocumentSemanticTokens = [];
var currentDocumentSemanticTokensEditorNode = undefined;
var currentDocumentExtraInfoDecorations = [];
var awaitingDocumentDecorations_action = undefined;
var awaitingDocumentDecorations = false;
var oldInlineDecorations = [];
function get_style_rule_value(e, t) {
  return "blue";
}
function syncOutlineView(e) {}
function clearCurrentEditorBreakpoints() {
  if (currentBreakpointDecorations.length > 0) {
    currentBreakpointDecorations.forEach((e) => {
      editor.deltaDecorations(e, []);
    });
  }
}
function clearEditorDecorations() {
  lastEditorDecorations = editor.deltaDecorations(lastEditorDecorations, []);
}
function clearEditor() {
  clearAllWidgets();
  removeAllAddinWidgets();
  clearCurrentEditorBreakpoints();
  clearEditorDecorations();
}
var lastEditorDecorations = [];
var lastEditorDecorations_LineSeperators = [];
var currentBreakpointDecorations = [];
const tokenTypes = [
  "basicClass",
  "basicModule",
  "basicVariable",
  "basicField",
  "basicUDT",
  "basicParameterByRef",
  "basicParameterByVal",
  "basicLibrary",
  "basicInterface",
  "basicBuiltInDataType",
  "basicConstant",
  "basicEnum",
  "basicEnumMember",
  "basicKeyword",
  "basicLiteralString",
  "basicOperator",
  "basicGenericDataType",
  "basicGenericValue",
  "basicReturnValue",
  "basicMe",
  "basicComment",
  "basicNamedArgument",
  "basicMultiLineSeperator",
  "basicLateBoundFunction",
  "basicLineLabel",
  "basicLineNumber",
  "basicLiteralNumeric",
  "basicLiteralBoolean",
  "basicLiteralNull",
  "basicLiteralNothing",
  "basicLiteralEmpty",
  "basicLiteralDate",
  "basicConditionalCompilationDirective",
  "basicConditionalCompilationExcludedCode",
  "basicVariableUndeclared",
  "basicFunction",
  "basicDeclareFunction",
  "basicSub",
  "basicDeclareSub",
  "basicPropertyGet",
  "basicPropertyLet",
  "basicPropertySet",
  "basicGlobalVariablePrivate",
  "basicGlobalVariablePublic",
  "basicAttribute",
  "basicLineContinuationCharacter",
];
function addStickyScrollLinesToVisibleRanges(e, t, o) {
  e.forEach((e) => {
    if (e.start <= o && e.end >= o) {
      t.push({ startLineNumber: e.start, endLineNumber: e.start });
    }
  });
}
function syncVisibleSemanticTokens() {
  if (!currentDocumentSemanticTokens) return;
  if (!currentDocumentSemanticTokensEditorNode) return;
  if (
    openEditors.selectedEditorNode !== currentDocumentSemanticTokensEditorNode
  )
    return;
  const e = currentDocumentSemanticTokens.length;
  var t = [];
  let o = editor.getVisibleRanges();
  if (o.length == 0) return;
  let n = o[0].startLineNumber;
  if (cachedFoldingRanges && liveIDEOptions["stickyScrolling"]) {
    addStickyScrollLinesToVisibleRanges(cachedFoldingRanges, o, n);
  }
  var i = 0;
  var r = 0;
  while (r < e) {
    const e = currentDocumentSemanticTokens[r];
    const n = currentDocumentSemanticTokens[r + 1];
    const s = currentDocumentSemanticTokens[r + 2];
    const a = currentDocumentSemanticTokens[r + 3];
    const l = currentDocumentSemanticTokens[r + 4];
    o.every((o) => {
      let i = o.startLineNumber;
      let r = o.endLineNumber;
      let l = 2;
      if (e >= i - l && e <= r + l) {
        t.push({
          range: new monaco.Range(e + 1, n + 1, e + 1, n + 1 + s),
          options: { inlineClassName: tokenTypes[a] },
        });
        return false;
      }
      return true;
    });
    r += 5;
    i++;
  }
  lastEditorDecorations = editor.deltaDecorations(lastEditorDecorations, t);
  if (codeHintsVisibility !== 0) {
    var s = document.querySelector(":root");
    var a = [];
    var l = 0;
    currentDocumentExtraInfoDecorations.forEach((e) => {
      o.every((t) => {
        let o = t.startLineNumber;
        let n = t.endLineNumber;
        let i = 2;
        if (e.line >= o - i && e.line <= n + i) {
          var r = "" + l;
          if (l < 100) r = "0" + r;
          if (l < 10) r = "0" + r;
          s.style.setProperty("--inlineComment" + r, '""');
          s.style.setProperty(
            "--inlineComment" + r,
            '"' +
              (e.info.charAt(0) === "=" ? "" : "🠈 ") +
              e.info.replace(/_\s*\r?\n/g, "").replaceAll('"', '\\"')
          );
          a.push({
            range: new monaco.Range(e.line, 99999999, e.line, 99999999),
            options: {
              afterContentClassName: "inlineDecoration inlineDecoration" + r,
            },
          });
          return false;
        }
        return true;
      });
      l++;
    });
    oldInlineDecorations = editor.deltaDecorations(oldInlineDecorations, a);
  }
}
function getSemanticTokensForCurrentFile() {
  var e = openEditors.selectedEditorNode;
  var t = "twinbasic:" + e.fileNode.getFullPath();
  awaitingDocumentDecorations = true;
  lspSocket.request(
    "textDocument/getDecorations",
    { textDocument: { uri: t, version: e.fileNode.ideVersionId } },
    (t) => {
      parseDocumentDecorations(e, t.result, 0);
    }
  );
}
function parseDocumentDecorations(e, t, o) {
  if (!t) return;
  if (openEditors.selectedEditorNode !== e) return;
  if (o) {
    if (o !== e.fileNode.ideVersionId) {
      return;
    }
  }
  currentDocumentSemanticTokens = t.semanticTokens;
  currentDocumentSemanticTokensEditorNode = e;
  currentDocumentExtraInfoDecorations = t.extraDecorations;
  let n = performance.now();
  syncVisibleSemanticTokens();
  var i = [];
  const r = t.lineSeperators;
  r.forEach((e) => {
    i.push({
      range: new monaco.Range(e, 1, e, 1),
      options: { isWholeLine: true, className: "procSplitterBar" },
    });
  });
  let s = performance.now();
  clearAllWidgets();
  const a = t.codeLens;
  a.forEach((e) => {
    addCodeLens(
      e.range.start.line + 1,
      e.range.start.character + 1,
      e.command.title,
      e.command.command,
      e.command.arguments
    );
  });
  const l = t.breakpoints;
  clearCurrentEditorBreakpoints();
  currentBreakpointDecorations = [];
  var d = [];
  l.forEach((e) => {
    currentBreakpointDecorations.push(
      editor.deltaDecorations(
        [],
        [
          {
            range: new monaco.Range(e.line, 1, e.line, 1),
            options: {
              glyphMarginClassName: "marginGlyph breakpointActiveGlyph",
            },
          },
        ]
      )
    );
    d.push(e.line);
  });
  resyncBookmarks(e.fileNode.getFullPath());
  openEditors.selectedEditorNode.monacoModelInstance.cachedBreakpointLines = d;
  outlinePanel.syncSymbols(t.symbols);
  codeComboSelectors.syncScopes(t.scopes);
  lastEditorDecorations_LineSeperators = editor.deltaDecorations(
    lastEditorDecorations_LineSeperators,
    i
  );
  awaitingDocumentDecorations = false;
  var c = awaitingDocumentDecorations_action;
  awaitingDocumentDecorations_action = undefined;
  if (c) c();
  if (performance.now() - revealedLineTime < 700) {
    revealLineInEditor(
      revealedLine,
      revealedLineColumn,
      revealedLineViewPortTop
    );
  }
}
var hoverTooltip;
var tooltipTimer = undefined;
var isHoveringOnTooltip = false;
function initTooltips() {
  hoverTooltip = document.getElementById("hoverTooltip");
  hoverTooltip.onmouseenter = () => {
    isHoveringOnTooltip = true;
  };
  hoverTooltip.onmouseleave = () => {
    isHoveringOnTooltip = false;
    unsetTooltip();
  };
}
function showTooltipNow() {
  hoverTooltip.style.display = "block";
}
function hideTooltipNow() {
  if (!isHoveringOnTooltip) {
    hoverTooltip.style.display = "none";
  }
  if (tooltipTimer) clearTimeout(tooltipTimer);
  tooltipTimer = undefined;
}
function setTooltip(e, t, o) {
  if (!e) {
    hideTooltipNow();
    return;
  }
  if (e) {
    hoverTooltip.style.left = t + "px";
    hoverTooltip.style.top = o + "px";
    hoverTooltip.innerText = e;
    tooltipTimer = setTimeout(showTooltipNow, 1e3);
  }
}
function setTooltipPosition(e, t) {
  if (hoverTooltip.style.display == "none") {
    hoverTooltip.style.left = e + "px";
    hoverTooltip.style.top = t + "px";
  }
}
function unsetTooltip() {
  if (!isHoveringOnTooltip) {
    if (tooltipTimer) clearTimeout(tooltipTimer);
    tooltipTimer = undefined;
    hideTooltipNow();
  }
}
var g_Elevated = false;
var rootMenu1;
var rootMenuFile;
var rootMenuEdit;
var rootMenuView;
var rootMenuProject;
var rootMenuFormat;
var rootMenuDebug;
var rootMenuRun;
var rootMenuTools;
var rootMenuAddins;
var rootMenuWindows;
var rootMenuHelp;
var rootMenuText;
var rootMenuTextOuter;
var rootMenuTitleFull;
var rootMenu1fullScreen;
var rootMenu1FullScreenToggle;
var rootMenuAdmin;
var rootMenuDevTools;
var rootMenuMinimize;
var rootMenuMaximize;
var rootMenuClose;
var rootMenuMinimize2;
var rootMenuMaximize2;
var rootMenuClose2;
var trashIcon;
var restartIcon;
var undoIcon;
var redoIcon;
var commentIcon;
var uncommentIcon;
var indentIcon;
var unindentIcon;
var searchIcon;
var saveIcon;
var paramHintsIcon;
var designSwitchIcon;
var buildIcon;
var playIcon;
var pauseIcon;
var stopIcon;
var debugStepOverIcon;
var debugStepIntoIcon;
var debugStepOutIcon;
var runOrPreviewIcon;
var rootMenu2;
var rootStatusBar;
var runningProcessesContainer;
var isClosingProject;
var onCloseProjectComplete;
var isAdmin = false;
function showReferences() {
  showIndividualSetting("project.references");
}
function showIndividualSetting(e) {
  var t =
    fs.tree.rootFolder.entries[
      Object.keys(fs.tree.rootFolder.entries)[0]
    ].resolvePath("项目设置");
  if (t.openEditorNode) {
    configEditor_applyFilter(t.openEditorNode.domContainerInner.globalVars, e);
    openEditors.openFile(
      t,
      false,
      false,
      false,
      undefined,
      undefined,
      undefined
    );
  } else {
    afterInitConfigCallback = () => {
      configEditor_applyFilter(
        t.openEditorNode.domContainerInner.globalVars,
        e
      );
    };
    openEditors.openFile(
      t,
      false,
      false,
      false,
      undefined,
      undefined,
      undefined
    );
  }
}
function exportFileTo(e, t, o) {
  var n = 0;
  if (o) n += 1;
  root.exportFile(e, t, o);
}
function exportProjectTo(e, t) {
  var o = 0;
  if (t) o += 1;
  root.exportProject(e, t);
}
async function getExportPath(e, t) {
  if (!t) t = "Export Project Files To...";
  exportPath = await hostAppObject.ChooseFolder(
    t,
    projectFilePath
      ? projectFilePath.substring(0, projectFilePath.lastIndexOf("\\"))
      : ""
  );
  if (exportPath && exportPath.length > 0) e(exportPath);
}
function exportProject() {
  getProjectSettings((e) => {
    var t = e["project.exportPath"];
    var o = e["project.exportPathIsV2"];
    var n = e["project.exportVerbose"];
    if (t) {
      if (!o) t = t + "${ProjectName}\\";
      exportProjectTo(t, n);
    } else {
      getExportPath((e) => {
        exportProjectTo(e + "${ProjectName}\\", n);
      });
    }
  });
}
var psuedoEventArgs = { stopPropagation() {} };
function debugOutputLineCopyPaste(e) {}
function trimWhitespaceFromLastLineIfOnlyWhitespace(e) {
  let t = e.split("\n");
  if (t.length && !t[t.length - 1].trim()) {
    t[t.length - 1] = "";
  }
  return t.join("\n");
}
async function editorPaste(e, t) {
  const o = e.getSelection();
  if (!o) {
    return;
  }
  var n = parseInt(liveIDEOptions["tabSize"]);
  var i = " ".repeat(n);
  debugOutputLineCopyPaste("tabSpacesCount: " + n);
  debugOutputLineCopyPaste("tabSpacesString: '" + i + "'");
  debugSocket.request("readClipboardIDE", {}, (r) => {
    var s = r.body.text;
    var a = r.body.extraData;
    s = s.replaceAll("\t", i);
    var l = false;
    if (s.includes("\n")) {
      s = trimWhitespaceFromLastLineIfOnlyWhitespace(s);
      l = true;
    }
    var d = o.startLineNumber;
    var c = o.startColumn;
    var u = -1;
    var p = "";
    var f = false;
    var g = false;
    while (1) {
      var m = d == o.startLineNumber;
      var h = e
        .getModel()
        .getValueInRange({
          startLineNumber: d,
          startColumn: 1,
          endLineNumber: d,
          endColumn: c,
        });
      h = h.replace("\t", i);
      if (u != -1) {
        var v = h.trim();
        var y = v.charAt(v.length - 1);
        var b = v.charAt(v.length - 2);
        if (y == "_" && b == " ") {
          debugOutputLineCopyPaste(
            "previous reference point DISCARDED due to line continuation [" +
              h +
              "]"
          );
          u = -1;
        } else {
          debugOutputLineCopyPaste(
            "previous reference point confirmed after considering earlier line: [" +
              h +
              "]"
          );
          break;
        }
      }
      debugOutputLineCopyPaste("considering BEFORE line: [" + h + "]");
      var C = h.trim();
      if (C.length > 0) {
        u = h.search(/\S/);
        p = C;
        f = m;
        debugOutputLineCopyPaste(
          "   -> line contains code.  check previous line is not a continuation.  possible reference point at " +
            u
        );
      } else {
        if (m) {
          g = true;
        }
      }
      c = 99999999999;
      d--;
      if (d == 0) break;
    }
    debugOutputLineCopyPaste("BEFORE reference point: " + u);
    var E = p.split(" ");
    var I = E[0];
    var D = E.length > 1 ? E[1] : undefined;
    debugOutputLineCopyPaste("referencePointFirstWord: " + I);
    var S =
      I == "Class" ||
      I == "Module" ||
      I == "Interface" ||
      I == "CoClass" ||
      I == "With" ||
      I == "If" ||
      I == "ElseIf" ||
      I == "Else" ||
      I == "While" ||
      I == "Do" ||
      I == "For" ||
      I == "Select" ||
      I == "Case" ||
      (I == "Private" && D != "Declare" && D != "DeclareWide") ||
      (I == "Public" && D != "Declare" && D != "DeclareWide") ||
      I == "Friend" ||
      I == "Sub" ||
      I == "Function" ||
      I == "Property";
    if (I == "If" || I == "ElseIf") {
      E = E.filter((e) => e.length > 0);
      var P = E.findIndex((e) => e == "Then");
      debugger;
      if (P === E.length) {
      } else if (E[P + 1] != "'") {
        S = false;
      }
    }
    debugOutputLineCopyPaste("referencePointIsStartOfBlock: " + S);
    debugOutputLineCopyPaste("referencePointIsCurrentLine: " + f);
    debugOutputLineCopyPaste("insertionPointIsInBeginingWhitespace: " + g);
    debugger;
    var w = s.trim().split(/\s+/).shift();
    debugOutputLineCopyPaste("clipboardFirstWord: " + w);
    var T =
      w == "End" ||
      w == "Next" ||
      w == "Loop" ||
      w == "Else" ||
      w == "ElseIf" ||
      w == "Wend" ||
      w == "Case";
    if (T) {
      debugger;
      if (!S) {
        debugger;
        u -= n;
        if (u < 0) u = 0;
      }
    } else {
      if (S) {
        debugOutputLineCopyPaste("searching FORWARDS ***********");
        u += n;
        var L = -1;
        var M = "";
        var x = o.startLineNumber;
        var O = f ? true : false;
        var k = e.getModel().getLineCount();
        while (x <= k) {
          h = e
            .getModel()
            .getValueInRange({
              startLineNumber: x,
              startColumn: 1,
              endLineNumber: x,
              endColumn: 99999999999,
            });
          h = h.replace("\t", i);
          if (O) {
            debugOutputLineCopyPaste(
              "ignoring line due to continuation: [" + h + "]"
            );
          } else {
            debugOutputLineCopyPaste("considering AFTER line: [" + h + "]");
            C = h.trim();
            if (C.length > 0) {
              L = h.search(/\S/);
              M = C;
              break;
            }
          }
          v = h.trim();
          y = v.charAt(v.length - 1);
          b = v.charAt(v.length - 2);
          if (y == "_" && b == " ") {
            O = true;
          } else {
            O = false;
          }
          x++;
        }
        if (L != -1) {
          var N = M.split(" ").shift();
          debugOutputLineCopyPaste("referencePointFirstWordAFTER: " + N);
          var R =
            N == "End" ||
            N == "Next" ||
            N == "Loop" ||
            N == "Else" ||
            N == "ElseIf" ||
            N == "Wend" ||
            N == "Case";
          debugOutputLineCopyPaste("referencePointIsEndOfBlock: " + R);
          debugOutputLineCopyPaste("AFTER reference point: " + L);
          if (!R) {
            debugOutputLineCopyPaste("Using AFTER reference point");
            u = L;
          }
        }
      }
    }
    debugOutputLineCopyPaste("INSERTION REFERENCE POINT: " + u);
    if (u == -1) u = 0;
    if (s.slice(-1) == "\n") {
      s = s + " ".repeat(u);
    }
    e.focus();
    if (g) {
      if (a != -1) {
        s = " ".repeat(a) + s;
      } else {
        let e = s.split(/\r?\n/);
        let t = 0;
        let o = false;
        e.every((e) => {
          if (t == 0) {
            if (e.charAt(0) == " ") {
              return false;
            }
            var i = e.split(" ");
            var r = i[0];
            var a = i[1];
            o =
              r == "Class" ||
              r == "Module" ||
              r == "Interface" ||
              r == "CoClass" ||
              r == "With" ||
              r == "If" ||
              r == "ElseIf" ||
              r == "Else" ||
              r == "While" ||
              r == "Do" ||
              r == "For" ||
              r == "Select" ||
              r == "Case" ||
              (r == "Private" && a != "Declare" && a != "DeclareWide") ||
              (r == "Public" && a != "Declare" && a != "DeclareWide") ||
              r == "Friend" ||
              r == "Sub" ||
              r == "Function" ||
              r == "Property";
            debugger;
          } else {
            let t = e.search(/\S/);
            if (t != -1) {
              if (o && t >= n) {
                t -= n;
              }
              s = " ".repeat(t) + s;
              return false;
            }
          }
          t++;
          return true;
        });
      }
    }
    var B = -1;
    let A = s.split(/\r?\n/);
    let F = 0;
    var _ = "";
    debugger;
    A.forEach((e) => {
      let o = e.search(/\S/);
      if (o !== -1) {
        if (t) {
          e = e.substring(0, o) + "' " + e.substring(o);
        }
      }
      if (B == -1) {
        B = o;
      }
      if (F > 0 || g) {
        let t = o;
        if (t == -1) {
        } else {
          var n = t - B;
          var i = (u == -1 ? 0 : u) + n;
          if (t < i) {
            e = " ".repeat(i - t) + e;
          } else if (t > i && i >= 0) {
            e = e.substring(t - i);
          }
        }
        if (!g || _.length) _ += "\r\n";
        _ += e;
      } else {
        _ += e;
      }
      F++;
    });
    if (g) {
      o.startColumn = 1;
    }
    if (l) {
      var H = e
        .getModel()
        .getValueInRange({
          startLineNumber: o.endLineNumber,
          startColumn: 1,
          endLineNumber: o.endLineNumber,
          endColumn: 99999999999,
        });
      var V = H.search(/\S/);
      if (V !== -1) {
        if (V > o.endColumn) {
          o.endColumn = V + 1;
        }
      }
    }
    debugger;
    e.executeEdits("clipboard", [
      { range: o, text: _, forceMoveMarkers: true },
    ]);
  });
}
async function editorPasteOld(e) {
  e.focus();
  const t = await navigator.clipboard.readText();
  const o = e.getSelection();
  if (!o) {
    return;
  }
  e.executeEdits("clipboard", [{ range: o, text: t, forceMoveMarkers: true }]);
}
async function editorCut(e) {
  await e.trigger("twinbasic", "editor.action.clipboardCopyAction");
  await editorDelete(e);
}
async function editorDelete(e) {
  e.focus();
  const t = e.getSelection();
  if (!t) {
    return;
  }
  e.executeEdits("clipboard", [{ range: t, text: "", forceMoveMarkers: true }]);
}
function editorSelectAll(e) {
  const t = e.getModel().getFullModelRange();
  e.setSelection(t);
  e.focus();
}
function initTopLevelMenus() {
  rootMenu1 = document.getElementById("rootMenu1");
  rootMenuFile = document.getElementById("rootMenuFile");
  rootMenuEdit = document.getElementById("rootMenuEdit");
  rootMenuView = document.getElementById("rootMenuView");
  rootMenuProject = document.getElementById("rootMenuProject");
  rootMenuFormat = document.getElementById("rootMenuFormat");
  rootMenuDebug = document.getElementById("rootMenuDebug");
  rootMenuRun = document.getElementById("rootMenuRun");
  rootMenuTools = document.getElementById("rootMenuTools");
  rootMenuAddins = document.getElementById("rootMenuAddins");
  rootMenuWindows = document.getElementById("rootMenuWindows");
  rootMenuHelp = document.getElementById("rootMenuHelp");
  rootMenuFile.navigateNextMenu = showEditMenu;
  rootMenuEdit.navigateNextMenu = showViewMenu;
  rootMenuView.navigateNextMenu = showProjectMenu;
  rootMenuProject.navigateNextMenu = showFormatMenu;
  rootMenuFormat.navigateNextMenu = showDebugMenu;
  rootMenuDebug.navigateNextMenu = showRunMenu;
  rootMenuRun.navigateNextMenu = showToolsMenu;
  rootMenuTools.navigateNextMenu = showAddinsMenu;
  rootMenuAddins.navigateNextMenu = showWindowsMenu;
  rootMenuWindows.navigateNextMenu = showHelpMenu;
  rootMenuEdit.navigatePrevMenu = showFileMenu;
  rootMenuView.navigatePrevMenu = showEditMenu;
  rootMenuProject.navigatePrevMenu = showViewMenu;
  rootMenuFormat.navigatePrevMenu = showProjectMenu;
  rootMenuDebug.navigatePrevMenu = showFormatMenu;
  rootMenuRun.navigatePrevMenu = showDebugMenu;
  rootMenuTools.navigatePrevMenu = showRunMenu;
  rootMenuAddins.navigatePrevMenu = showToolsMenu;
  rootMenuWindows.navigatePrevMenu = showAddinsMenu;
  rootMenuHelp.navigatePrevMenu = showWindowsMenu;
  rootMenu2 = document.getElementById("rootMenu2");
  rootMenuText = document.getElementById("rootMenuText");
  rootMenuTextOuter = document.getElementById("rootMenuTextOuter");
  rootMenuTitleFull = document.getElementById("rootMenuTitleFull");
  rootMenuTextOuter.onmousedown = () => {
    hostAppObject.DragFormStart("ignore");
  };
  rootMenuAdmin = document.getElementById("rootMenuAdmin");
  rootMenuDevTools = document.getElementById("rootMenuDevTools");
  rootMenuMinimize = document.getElementById("rootMenuMinimize");
  rootMenuMaximize = document.getElementById("rootMenuMaximize");
  rootMenuClose = document.getElementById("rootMenuClose");
  rootMenuMinimize2 = document.getElementById("rootMenuMinimize2");
  rootMenuMaximize2 = document.getElementById("rootMenuMaximize2");
  rootMenuClose2 = document.getElementById("rootMenuClose2");
  restartIcon = document.getElementById("restartIcon");
  trashIcon = document.getElementById("trashIcon");
  undoIcon = document.getElementById("undoIcon");
  redoIcon = document.getElementById("redoIcon");
  commentIcon = document.getElementById("commentIcon");
  uncommentIcon = document.getElementById("uncommentIcon");
  indentIcon = document.getElementById("indentIcon");
  unindentIcon = document.getElementById("unindentIcon");
  searchIcon = document.getElementById("searchIcon");
  saveIcon = document.getElementById("saveIcon");
  paramHintsIcon = document.getElementById("paramHintsIcon");
  buildIcon = document.getElementById("buildIcon");
  designSwitchIcon = document.getElementById("designSwitchIcon");
  playIcon = document.getElementById("playIcon");
  pauseIcon = document.getElementById("pauseIcon");
  stopIcon = document.getElementById("stopIcon");
  debugStepOverIcon = document.getElementById("debugStepOverIcon");
  debugStepIntoIcon = document.getElementById("debugStepIntoIcon");
  debugStepOutIcon = document.getElementById("debugStepOutIcon");
  runOrPreviewIcon = document.getElementById("runOrPreviewIcon");
  runningProcessesContainer = document.getElementById(
    "runningProcessesContainer"
  );
  rootStatusBar = document.getElementById("rootStatusBar");
  rootMenuFile.onmousedown = (e) => {
    if (e.button === 0) showFileMenu();
  };
  rootMenuFile.onmouseenter = () => {
    if (currentSelectedTopMenu && currentSelectedTopMenu !== rootMenuFile)
      showFileMenu();
  };
  rootMenuEdit.onmousedown = (e) => {
    if (e.button === 0) showEditMenu();
  };
  rootMenuEdit.onmouseenter = () => {
    if (currentSelectedTopMenu && currentSelectedTopMenu !== rootMenuEdit)
      showEditMenu();
  };
  rootMenuView.onmousedown = (e) => {
    if (e.button === 0) showViewMenu();
  };
  rootMenuView.onmouseenter = () => {
    if (currentSelectedTopMenu && currentSelectedTopMenu !== rootMenuView)
      showViewMenu();
  };
  rootMenuProject.onmousedown = (e) => {
    if (e.button === 0) showProjectMenu();
  };
  rootMenuProject.onmouseenter = () => {
    if (currentSelectedTopMenu && currentSelectedTopMenu !== rootMenuProject)
      showProjectMenu();
  };
  rootMenuFormat.onmousedown = (e) => {
    if (e.button === 0) showFormatMenu();
  };
  rootMenuFormat.onmouseenter = () => {
    if (currentSelectedTopMenu && currentSelectedTopMenu !== rootMenuFormat)
      showFormatMenu();
  };
  rootMenuDebug.onmousedown = (e) => {
    if (e.button === 0) showDebugMenu();
  };
  rootMenuDebug.onmouseenter = () => {
    if (currentSelectedTopMenu && currentSelectedTopMenu !== rootMenuDebug)
      showDebugMenu();
  };
  rootMenuRun.onmousedown = (e) => {
    if (e.button === 0) showRunMenu();
  };
  rootMenuRun.onmouseenter = () => {
    if (currentSelectedTopMenu && currentSelectedTopMenu !== rootMenuRun)
      showRunMenu();
  };
  rootMenuTools.onmousedown = (e) => {
    if (e.button === 0) showToolsMenu();
  };
  rootMenuTools.onmouseenter = () => {
    if (currentSelectedTopMenu && currentSelectedTopMenu !== rootMenuTools)
      showToolsMenu();
  };
  rootMenuAddins.onmousedown = (e) => {
    if (e.button === 0) showAddinsMenu();
  };
  rootMenuAddins.onmouseenter = () => {
    if (currentSelectedTopMenu && currentSelectedTopMenu !== rootMenuAddins)
      showAddinsMenu();
  };
  rootMenuWindows.onmousedown = (e) => {
    if (e.button === 0) showWindowsMenu();
  };
  rootMenuWindows.onmouseenter = () => {
    if (currentSelectedTopMenu && currentSelectedTopMenu !== rootMenuWindows)
      showWindowsMenu();
  };
  rootMenuHelp.onmousedown = (e) => {
    if (e.button === 0) showHelpMenu();
  };
  rootMenuHelp.onmouseenter = () => {
    if (currentSelectedTopMenu && currentSelectedTopMenu !== rootMenuHelp)
      showHelpMenu();
  };
  trashIcon.onclick = () => {
    debugSocket.build(true);
  };
  restartIcon.onclick = () => {
    restartCompilerSafely();
  };
  undoIcon.onclick = () => {
    openEditors.selectedEditorNode.fileHandler.undo(
      openEditors.selectedEditorNode
    );
  };
  redoIcon.onclick = () => {
    openEditors.selectedEditorNode.fileHandler.redo(
      openEditors.selectedEditorNode
    );
  };
  commentIcon.onclick = () => {
    editor.trigger("twinbasic", "editor.action.addCommentLine");
    editor.focus();
  };
  uncommentIcon.onclick = () => {
    editor.trigger("twinbasic", "editor.action.removeCommentLine");
    editor.focus();
  };
  indentIcon.onclick = () => {
    editor.trigger("twinbasic", "editor.action.indentLines");
    editor.focus();
  };
  unindentIcon.onclick = () => {
    editor.trigger("twinbasic", "editor.action.outdentLines");
    editor.focus();
  };
  searchIcon.onclick = findInFiles;
  saveIcon.onclick = () => {
    if (openEditors.hasDirtyEditors()) {
      openEditors.saveAll();
    } else {
      if (!projectFilePath) {
        saveProjectAs(() => {});
      }
    }
    editor.focus();
  };
  buildIcon.onclick = () => {
    debugSocket.build();
  };
  designSwitchIcon.onclick = () => {
    toggleFormDesign();
  };
  playIcon.onclick = () => {
    debugSocket.continue();
  };
  pauseIcon.onclick = () => {
    debugSocket.breakInto();
  };
  stopIcon.onclick = () => {
    debugSocket.stop();
  };
  debugStepOverIcon.onclick = () => {
    debugSocket.stepOver();
  };
  debugStepIntoIcon.onclick = () => {
    debugSocket.stepInto();
  };
  debugStepOutIcon.onclick = () => {
    debugSocket.stepOut();
  };
  runOrPreviewIcon.onclick = runOrPreviewClick;
  rootMenuDevTools.onclick = () => {
    hostAppObject.OpenDevTools("ignore");
  };
  rootMenuMinimize.onclick = () => {
    hostAppObject.MinimizeWindow("ignore");
    minimizeAllToolWIndows();
  };
  rootMenuMaximize.onclick = () => {
    if (rootMenuMaximize.classList.contains("isMaximized")) {
      hostAppObject.RestoreWindow("ignore");
    } else {
      hostAppObject.MaximizeWindow("ignore");
    }
  };
  rootMenuTextOuter.ondblclick = () => {
    rootMenuMaximize.onclick();
  };
  rootMenuClose.onclick = () => {
    hostAppObject.CloseWindow("ignore");
  };
  rootMenuMinimize2.onclick = rootMenuMinimize.onclick;
  rootMenuMaximize2.onclick = rootMenuMaximize.onclick;
  rootMenuClose2.onclick = rootMenuClose.onclick;
  window.chrome.webview.addEventListener("message", (e) => {
    if (typeof e.data === "string") {
      if (e.data === "WINDOW-NORMAL") {
        rootMenuMaximize.classList.remove("isMaximized");
        rootMenuMaximize2.classList.remove("isMaximized");
      } else if (e.data === "WINDOW-MAXIMIZED") {
        rootMenuMaximize.classList.add("isMaximized");
        rootMenuMaximize2.classList.add("isMaximized");
      } else if (e.data === "WINDOW-CLOSE") {
        closeProjectSafely(() => {
          hostAppObject.Exit("ignore");
        });
      } else if (e.data === "WINDOW-FOCUS") {
        restoreAllToolWIndows();
      }
    } else {
      handleToolWindowMessage(e.data);
    }
  });
  rootMenu1fullScreen = document.getElementById("rootMenu1fullScreen");
  rootMenu1fullScreen.onmousedown = () => {
    hostAppObject.DragFormStart("ignore");
  };
  rootMenu1FullScreenToggle = document.getElementById(
    "rootMenu1FullScreenToggle"
  );
  rootMenu1FullScreenToggle.onclick = () => {
    toggleFullScreenMode();
  };
  rootMenuMinimize2.onmousedown = (e) => {
    e.stopPropagation();
  };
  rootMenuMaximize2.onmousedown = (e) => {
    e.stopPropagation();
  };
  rootMenuClose2.onmousedown = (e) => {
    e.stopPropagation();
  };
  rootMenu1FullScreenToggle.onmousedown = (e) => {
    e.stopPropagation();
  };
  GetInitialWindowState();
  IsAdminCheck();
}
async function GetInitialWindowState() {
  var e = await hostAppObject.GetWindowState("ignore");
  if (e === "WINDOW-NORMAL") {
    rootMenuMaximize.classList.remove("isMaximized");
  } else if (e === "WINDOW-MAXIMIZED") {
    rootMenuMaximize.classList.add("isMaximized");
  }
}
async function IsAdminCheck() {
  isAdmin = await hostAppObject.IsAdmin("ignore");
  if (isAdmin) {
    rootMenuAdmin.innerText = "管理员身份";
    g_Elevated = true;
  } else {
  }
}
function restartCompilerSafely() {
  root.sendLiveBackupWorkerMessage("updateCacheNow", [], () => {
    root.forceTerminate();
  });
}
function closeProjectNow(e) {
  isClosingProject = true;
  onCloseProjectComplete = e;
  root.forceTerminate();
}
function failedToSaveAskToDiscard(e) {
  var t = createDOMElement(
    undefined,
    "div",
    "simpleMsgBox",
    "无法保存更改。  丢弃它们？"
  );
  showModalDialog(t, [
    {
      caption: "放弃更改",
      onclick: () => {
        hideModalDialog();
        closeProjectNow(e);
      },
    },
    {
      caption: "取消",
      onclick: hideModalDialog,
      isDefaultCancelAction: true,
    },
  ]);
}
function closeProjectSafely(e) {
  if (openEditors.hasDirtyEditors() || (!projectFilePath && projectIsLoaded)) {
    var t = createDOMElement(
      undefined,
      "div",
      "simpleMsgBox",
      "您已经对此项目进行了更改。 现在保存吗？"
    );
    showModalDialog(t, [
      {
        caption: "保存",
        onclick: () => {
          hideModalDialog();
          var t = () => {
            openEditors.saveAll();
            showModalProgressIndicator();
            root.onSaveFileComplete(
              () => {
                hideModalProgressIndicator();
                closeProjectNow(e);
              },
              () => {
                hideModalProgressIndicator();
                failedToSaveAskToDiscard(e);
              }
            );
          };
          if (!projectFilePath) {
            saveProjectAs(() => {
              t();
            });
          } else {
            t();
          }
        },
      },
      {
        caption: "放弃更改",
        onclick: () => {
          hideModalDialog();
          closeProjectNow(e);
        },
      },
      {
        caption: "取消",
        onclick: hideModalDialog,
        isDefaultCancelAction: true,
      },
    ]);
  } else {
    showModalProgressIndicator();
    root.onSaveFileComplete(
      () => {
        hideModalProgressIndicator();
        closeProjectNow(e);
      },
      () => {
        hideModalProgressIndicator();
        failedToSaveAskToDiscard(e);
      }
    );
  }
}
function findInFiles() {
  var e = createDOMElement(
    undefined,
    "div",
    "simpleMsgBoxNoImage",
    "输入搜索字符串(仅限纯文本搜索):"
  );
  var t = createDOMElement(e, "input", "searchInputBox");
  var o = createDOMElement(e, "input", "searchOption");
  o.type = "checkbox";
  o.checked = searchInsidePackages;
  o.onclick = () => {
    searchInsidePackages = o.checked ? true : false;
  };
  var n = createDOMElement(
    e,
    "div",
    "searchOptionText",
    "搜索内部引用的包"
  );
  n.onclick = () => {
    o.checked = !o.checked;
    o.onclick();
  };
  createDOMElement(e, "br");
  var i = createDOMElement(e, "input", "searchOption");
  i.type = "checkbox";
  i.checked = searchCaseSensitive;
  i.onclick = () => {
    searchCaseSensitive = i.checked ? true : false;
  };
  var r = createDOMElement(e, "div", "searchOptionText", "Match case");
  r.onclick = () => {
    i.checked = !i.checked;
    i.onclick();
  };
  createDOMElement(e, "br");
  var s = createDOMElement(e, "input", "searchOption");
  s.type = "checkbox";
  s.checked = searchWholeWordOnly;
  s.onclick = () => {
    searchWholeWordOnly = s.checked ? true : false;
  };
  var a = createDOMElement(
    e,
    "div",
    "searchOptionText",
    "仅匹配整个单词"
  );
  a.onclick = () => {
    s.checked = !s.checked;
    s.onclick();
  };
  var l = "";
  if (editor && !codePanelMainInnerMonacoContainer.classList.contains("hide")) {
    try {
      var d = editor.getSelection();
      l = editor.getModel().getValueInRange(d);
      if (l.length == 0) {
        l = editor
          .getModel()
          .getWordAtPosition({
            lineNumber: d.startLineNumber,
            column: d.startColumn,
          }).word;
      }
      t.value = l;
    } catch (e) {}
  }
  t.onkeydown = (e) => {
    if (e.key === "Escape") {
      hideModalDialog();
    } else if (e.key === "Enter") {
      if (t.value.length > 0)
        debugSocket.findInFiles(t.value, o.checked, i.checked, s.checked);
      hideModalDialog();
    }
  };
  showModalDialog(e, [
    {
      caption: "在项目内搜索",
      onclick: () => {
        if (t.value.length > 0)
          debugSocket.findInFiles(t.value, o.checked, i.checked, s.checked);
        hideModalDialog();
      },
    },
    { caption: "取消", onclick: hideModalDialog },
  ]);
  t.focus();
  t.select();
}
function notSupportedMenuOption() {
  msgBox("抱歉，此菜单选项尚未实现");
}
function showFileMenu() {
  showContextMenu(
    rootMenuFile,
    rootMenuFile.offsetLeft,
    rootMenuFile.offsetTop + rootMenuFile.offsetHeight,
    [
      {
        name: "新建项目...",
        action: () => {
          closeProjectSafely(() => {
            prepareToStart();
            showFrontPageDialog(showNewProjects);
          });
        },
      },
      {
        name: "打开项目...",
        action: () => {
          closeProjectSafely(() => {
            openProject();
          });
        },
      },
      {
        name: "打开最近项目...",
        action: () => {
          closeProjectSafely(() => {
            prepareToStart();
            showFrontPageDialog(showRecentProjects);
          });
        },
      },
      { name: "关闭项目", action: closeProjectSafely },
      {},
      {
        name: "保存项目",
        action: () => {
          saveProject();
        },
      },
      {
        name: "项目另存为...",
        action: () => {
          saveProjectAs(() => {
            saveIcon.onclick();
          });
        },
      },
      {},
      {
        name: "导出项目",
        action: () => {
          exportProject();
        },
      },
      {},
      {
        name: "保存当前文档",
        action: () => {
          openEditors.save(openEditors.selectedEditorNode);
        },
        isHidden: true,
      },
      {
        name: "当前文档另存为...",
        action: () => {
          notSupportedMenuOption();
        },
        isHidden: true,
      },
      {},
      {
        name: "编译...",
        action: () => {
          buildIcon.onclick();
        },
      },
      {
        name: "清除...",
        action: () => {
          trashIcon.onclick();
        },
      },
      {},
      {
        name: "Exit",
        action: () => {
          rootMenuClose.onclick();
        },
      },
    ]
  );
}
function showEditMenu() {
  showContextMenu(
    rootMenuEdit,
    rootMenuEdit.offsetLeft,
    rootMenuEdit.offsetTop + rootMenuEdit.offsetHeight,
    [
      {
        name: "撤销",
        action: () => {
          editor.focus();
          editor.getModel().undo();
        },
      },
      {
        name: "重做",
        action: () => {
          editor.focus();
          editor.getModel().redo();
        },
      },
      {},
      {
        name: "剪切",
        action: () => {
          cutOrCopy(editor, true);
        },
      },
      {
        name: "复制",
        action: () => {
          cutOrCopy(editor, false);
          editor.focus();
        },
      },
      {
        name: "粘贴",
        action: () => {
          editorPaste(editor);
        },
      },
      {
        name: "粘贴为注释",
        action: () => {
          editorPaste(editor, true);
        },
      },
      {
        name: "删除",
        action: () => {
          editorDelete(editor);
        },
      },
      {
        name: "全选",
        action: () => {
          editorSelectAll(editor);
        },
      },
      {},
      {
        name: "查找...",
        action: () => {
          editor.focus();
          editor.trigger("twinbasic", "tbFind");
        },
      },
      {
        name: "替换...",
        action: () => {
          editor.focus();
          editor.trigger("twinbasic", "tbFindReplace");
        },
      },
      {
        name: "在项目中查找...",
        action: () => {
          searchIcon.onclick();
        },
      },
      {},
      {
        name: "缩进...",
        action: () => {
          indentIcon.onclick();
        },
      },
      {
        name: "凸出...",
        action: () => {
          unindentIcon.onclick();
        },
      },
    ]
  );
}
function showViewMenu() {
  showContextMenu(
    rootMenuView,
    rootMenuView.offsetLeft,
    rootMenuView.offsetTop + rootMenuView.offsetHeight,
    [
      {
        name: "代码",
        action: () => {
          switchToCodePart();
        },
      },
      {
        name: "对象",
        action: () => {
          switchToFormPart();
        },
      },
      {},
      {
        name: "定义",
        action: () => {
          notSupportedMenuOption();
        },
        isHidden: true,
      },
      {},
      {
        name: "缩放",
        action: () => {
          notSupportedMenuOption();
        },
        isHidden: true,
      },
    ]
  );
}
function showProjectMenu() {
  showContextMenu(
    rootMenuProject,
    rootMenuProject.offsetLeft,
    rootMenuProject.offsetTop + rootMenuProject.offsetHeight,
    [
      {
        name: "添加",
        detail: "➤",
        hoverAction: (e) => {
          showContextMenuAddComponent({
            clientX:
              rootMenuProject.offsetLeft + e.getBoundingClientRect().width,
            clientY: rootMenuProject.offsetTop + e.getBoundingClientRect().top,
          });
        },
        unhoverAction: () => {
          SubMenuRelease();
        },
      },
      {},
      {
        name: "引用...",
        action: () => {
          showReferences();
        },
      },
      {
        name: "项目属性...",
        action: () => {
          var e =
            fs.tree.rootFolder.entries[
              Object.keys(fs.tree.rootFolder.entries)[0]
            ].resolvePath("项目设置");
          openEditors.openFile(e);
        },
      },
      {},
      {
        name: "打开项目文件夹...",
        action: () => {
          root.Shell(
            'explorer "' +
              projectFilePath.substring(0, projectFilePath.lastIndexOf("\\")) +
              '"',
            true
          );
        },
      },
      {
        name: "打开编译输出文件夹...",
        action: () => {
          root.Shell(
            'explorer "' +
              projectBuildPath.substring(
                0,
                projectBuildPath.lastIndexOf("\\")
              ) +
              '"',
            true
          );
        },
      },
    ]
  );
}
function showFormatMenu() {
  showContextMenu(
    rootMenuFormat,
    rootMenuFormat.offsetLeft,
    rootMenuFormat.offsetTop + rootMenuFormat.offsetHeight,
    [
      {
        name: "对齐",
        detail: "➤",
        action: () => {
          notSupportedMenuOption();
        },
        isHidden: true,
      },
      {
        name: "使尺寸相同",
        detail: "➤",
        action: () => {
          notSupportedMenuOption();
        },
        isHidden: true,
      },
      {},
      {
        name: "尺寸到网格",
        action: () => {
          notSupportedMenuOption();
        },
        isHidden: true,
      },
      {},
      {
        name: "在窗体内居中",
        detail: "➤",
        action: () => {
          notSupportedMenuOption();
        },
        isHidden: true,
      },
      {},
      {
        name: "其他",
        detail: "➤",
        action: () => {
          notSupportedMenuOption();
        },
        isHidden: true,
      },
      {},
      {
        name: "锁定控件",
        action: () => {
          notSupportedMenuOption();
        },
        isHidden: true,
      },
    ]
  );
}
function showDebugMenu() {
  showContextMenu(
    rootMenuDebug,
    rootMenuDebug.offsetLeft,
    rootMenuDebug.offsetTop + rootMenuDebug.offsetHeight,
    [
      {
        name: "单步执行",
        action: () => {
          debugStepIntoIcon.onclick(psuedoEventArgs);
        },
      },
      {
        name: "单步跳过",
        action: () => {
          debugStepOverIcon.onclick(psuedoEventArgs);
        },
      },
      {},
      {
        name: "添加监视",
        action: () => {
          watches_onTreeDblClick(psuedoEventArgs);
        },
      },
      {},
      {
        name: "清除所有断点",
        action: () => {
          debugSocket.request("clearAllBreakpoints", {}, (e) => {
            clearCurrentDocumentBreakpoints();
          });
        },
      },
      {},
      {
        name: "设置下一步语句(跳到行)",
        action: () => {
          setCurrentThreadExecutionPoint();
        },
        isHidden: activeBreakLineNumber > 0 ? false : true,
      },
    ]
  );
}
function showRunMenu() {
  showContextMenu(
    rootMenuRun,
    rootMenuRun.offsetLeft,
    rootMenuRun.offsetTop + rootMenuRun.offsetHeight,
    [
      {
        name: "开始",
        action: () => {
          notSupportedMenuOption();
        },
        isHidden: true,
      },
      {
        name: "以全编译方式启动",
        action: () => {
          notSupportedMenuOption();
        },
        isHidden: true,
      },
      {
        name: "中断",
        action: () => {
          pauseIcon.onclick(psuedoEventArgs);
        },
      },
      {
        name: "结束",
        action: () => {
          stopIcon.onclick(psuedoEventArgs);
        },
      },
      {
        name: "重新启动",
        action: () => {
          notSupportedMenuOption();
        },
        isHidden: true,
      },
    ]
  );
}
function showAddinsMenu() {
  root.getAddinsList((e) => {
    var t = [];
    e.forEach((e) => {
      t.push({
        name: e.name,
        action: () => {
          notSupportedMenuOption();
        },
        iconClass: "tickIcon",
      });
    });
    if (t.length == 0) {
      t.push({ name: "{no addins loaded}" });
    }
    showContextMenu(
      rootMenuAddins,
      rootMenuAddins.offsetLeft,
      rootMenuAddins.offsetTop + rootMenuAddins.offsetHeight,
      t
    );
  });
}
function showToolsMenu() {
  showContextMenu(
    rootMenuTools,
    rootMenuTools.offsetLeft,
    rootMenuTools.offsetTop + rootMenuTools.offsetHeight,
    [
      {
        name: "添加过程...",
        action: () => {
          notSupportedMenuOption();
        },
        isHidden: true,
      },
      {
        name: "过程属性...",
        action: () => {
          notSupportedMenuOption();
        },
        isHidden: true,
      },
      {},
      {
        name: "IDE选项...",
        action: () => {
          showIDEOptions(() => {});
        },
      },
    ]
  );
}
function showWindowsMenu() {
  showContextMenu(
    rootMenuWindows,
    rootMenuWindows.offsetLeft,
    rootMenuWindows.offsetTop + rootMenuWindows.offsetHeight,
    [
      {
        name: "创建工具窗口",
        detail: "➤",
        hoverAction: (e) => {
          showContextMenu(
            undefined,
            rootMenuWindows.offsetLeft + e.getBoundingClientRect().width,
            rootMenuWindows.offsetTop + e.getBoundingClientRect().top,
            [
              {
                name: "问题面板",
                action: () => {
                  createToolWindowPROBLEMS();
                },
              },
              {
                name: "大纲面板",
                action: () => {
                  createToolWindowOUTLINE();
                },
              },
            ]
          );
        },
        unhoverAction: () => {
          SubMenuRelease();
        },
      },
      {},
      {
        name: "存储布局",
        detail: "➤",
        action: () => {
          notSupportedMenuOption();
        },
        isHidden: true,
      },
      {
        name: "保存布局...",
        action: () => {
          notSupportedMenuOption();
        },
        isHidden: true,
      },
      {
        name: "重置布局...",
        action: () => {
          var e = createDOMElement(
            undefined,
            "div",
            "simpleMsgBox",
            "这将重置面板布局数据。  您确定要这样做吗？\n\n之后，您将需要关闭并重新启动IDE才能看到更改。"
          );
          showModalDialog(e, [
            {
              caption: "重置面板布局数据",
              onclick: () => {
                hostAppObject.SaveIDESetting("LAYOUT", JSON.stringify({}));
                rootMenuClose.onclick();
              },
            },
            {
              caption: "取消",
              onclick: hideModalDialog,
              isDefaultCancelAction: true,
            },
          ]);
        },
      },
      {},
      {
        name: "主题",
        detail: "➤",
        hoverAction: (e) => {
          showContextMenu(
            undefined,
            rootMenuWindows.offsetLeft + e.getBoundingClientRect().width,
            rootMenuWindows.offsetTop + e.getBoundingClientRect().top,
            [
              {
                name: "深色",
                action: () => {
                  liveIDEOptions["colorTheme"] = "dark";
                  changedIdeOptions();
                },
              },
              {
                name: "浅色",
                action: () => {
                  liveIDEOptions["colorTheme"] = "light";
                  changedIdeOptions();
                },
              },
            ]
          );
        },
        unhoverAction: () => {
          SubMenuRelease();
        },
      },
      {},
      {
        name: "切换全屏模式",
        action: () => {
          toggleFullScreenMode();
        },
      },
    ]
  );
}
function showHelpMenu() {
  showContextMenu(
    rootMenuHelp,
    rootMenuHelp.offsetLeft,
    rootMenuHelp.offsetTop + rootMenuHelp.offsetHeight,
    [
      {
        name: "关于twinBASIC...",
        action: () => {
          notSupportedMenuOption();
        },
        isHidden: true,
      },
      {},
      {
        name: "帮助与支持(Discord服务器)",
        action: () => {
          discordIconDiv.onclick();
        },
      },
      {
        name: "帮助与支持(GitHub 仓库)",
        action: () => {
          githubIconDiv.onclick();
        },
      },
      {
        name: "Twitter (新闻推荐)",
        action: () => {
          twitterIconDiv.onclick();
        },
      },
      {},
      {
        name: "购买许可证",
        action: () => {
          root.Shell(
            'cmd.exe /c start "link" "https://twinbasic.com/preorder.html"'
          );
        },
      },
      {
        name: "输入许可证密钥",
        action: () => {
          onChangeLicence();
        },
      },
      {
        name: "给我们买一杯咖啡! (Ko-Fi)",
        action: () => {
          kofiIconDiv.onclick();
        },
      },
    ]
  );
}
var currentDragType = undefined;
const DRAG_PANEL_SECTION = 1;
const DRAG_TAB = 2;
const DRAG_TREE_NODE = 3;
function processShiftKey(e, t, o, n) {
  var i = false;
  if (e === o && !n.state) {
    n.state = !n.state;
    i = true;
  }
  if (n.state) {
    if (n.unShiftMode) {
      if (e.isSelected) {
        e.unselect();
      }
    } else {
      e.select();
    }
  }
  if (!i && (e === t || e === o)) {
    n.state = !n.state;
  }
}
function onDragPanelSectionStart(e, t) {
  startDropZone = t;
  currentDragType = DRAG_PANEL_SECTION;
  hideTooltipNow();
  e.dataTransfer.setData("text/plain", t.innerText);
}
function onDragPanelSectionDropped(e) {
  if (currentDragType !== DRAG_PANEL_SECTION) return;
  if (startDropZone.panelId !== currentDropZone.panelId) {
    var t = currentDropZone;
    if (!currentDropZone.panelDiv.isVerticalPanel) t = t.parentElement;
    assignToPanel(undefined, startDropZone, currentDropZone.panelDiv, t);
  }
}
function onDragPanelSectionHover(e, t, o) {
  if (currentDragType !== DRAG_PANEL_SECTION) return;
  e.preventDefault();
  var n = t.resizerDiv;
  if (!o) {
    if (t.parentNode.isVerticalPanel) {
      if (e.offsetY > t.sectionRoot.offsetHeight / 2) {
        if (t.nextPanelSection) {
          t = t.nextPanelSection;
          n = t.resizerDiv;
        }
      }
    } else {
      if (e.offsetX > t.sectionRoot.offsetWidth / 2) {
        if (t.nextPanelSection) {
          t = t.nextPanelSection;
          n = t.resizerDiv;
        }
      }
    }
  }
  if (currentDropZone && currentDropZone.resizerDiv) {
    currentDropZone.resizerDiv.classList.remove("panelMoveTarget");
    currentDropZone.resizerDiv.parentNode.classList.remove(
      "panelMoveTargetParent"
    );
  }
  currentDropZone = t;
  n.classList.add("panelMoveTarget");
  n.parentNode.classList.add("panelMoveTargetParent");
  e.dataTransfer.dropEffect = "move";
}
function onDragPanelSectionEnd(e, t) {
  if (currentDropZone && currentDropZone.resizerDiv) {
    currentDropZone.resizerDiv.classList.remove("panelMoveTarget");
    currentDropZone.resizerDiv.parentNode.classList.remove(
      "panelMoveTargetParent"
    );
  }
  currentDragType = undefined;
}
class treeView {
  constructor(e, t, o, n, i, r) {
    this.panelDiv = e;
    this.itemPaddingLeft = i ? i : 0;
    this.isSimpleList = r;
    this.rootFolder = new treeViewFolder(this, undefined, -1, o, true);
    this.selectedItems = [];
    this.selectedItem = undefined;
    this.lastShiftKeyEndPoint = undefined;
    this.allowMultiSelect = n;
    this.friendlyName = t;
    this.name = o;
    this.showFolderIcons = true;
    this.showItemIcons = true;
    this.emptyFolderText = r ? "" : "(empty)";
    this.caseSensitiveEntries = true;
    this.autoExpandOnSelect = true;
    this.showTooltips = true;
    this.showHiddenEntries = false;
    this.autoHideEntriesBeginningWithDot = false;
    this.additionalFolderClassNames = "";
  }
  activateRenameHandling(e) {
    setTimeout(() => {
      document.getElementById("renameInput").onblur = () => {
        var t = document.getElementById("renameInput");
        var o = t.cancelled ? undefined : t.value;
        if (e.rename) {
          e.rename(e, o);
        } else {
          e.tree.onRenameItem(e, o);
        }
        e.isRenaming = false;
        e.render();
      };
      document.getElementById("renameInput").focus();
      if (e.name.indexOf(".") != -1) {
        var t = e.name.split(".").pop();
        setTimeout(() => {
          document
            .getElementById("renameInput")
            .setSelectionRange(0, e.name.length - (t.length + 1));
        }, 0);
      } else {
        document.getElementById("renameInput").select();
      }
      document.getElementById("renameInput").onkeyup = (t) => {
        if (this.onRenameValidate) {
          if (
            !this.onRenameValidate(
              e,
              document.getElementById("renameInput").value
            )
          ) {
            document
              .getElementById("renameInput")
              .classList.add("invalidRename");
          } else {
            document
              .getElementById("renameInput")
              .classList.remove("invalidRename");
          }
        }
      };
      document.getElementById("renameInput").onkeydown = (e) => {
        if (e.key == "Enter") {
          document.getElementById("renameInput").blur();
          e.stopPropagation();
        }
        if (e.key == "Escape") {
          document.getElementById("renameInput").cancelled = true;
          document.getElementById("renameInput").value = "";
          document.getElementById("renameInput").blur();
          e.stopPropagation();
        }
      };
    }, 0);
  }
  getSelectedNonOverlappingNodes() {
    var e = [];
    this.selectedItems.forEach((t) => {
      var o = t.getFullPath();
      var n = false;
      var i = 0;
      e.forEach((r) => {
        var s = r.getFullPath();
        if (t.isFolder && s.indexOf(o + "/") == 0) {
          e.splice(i, 1);
        } else if (r.isFolder && o.indexOf(s + "/") == 0) {
          n = true;
          i++;
        } else {
          i++;
        }
      });
      if (!n) e.push(t);
    });
    return e;
  }
  getSelectedItemsIds() {
    var e = [];
    this.selectedItems.forEach((t) => {
      e.push(t.getFullPath());
    });
    return e;
  }
  getSelectedItemsCount() {
    return this.selectedItems.length;
  }
  hideHoverElement() {
    this.sectionRoot.classList.add("hideHoverElement");
  }
  unhideHoverElement() {
    this.sectionRoot.classList.remove("hideHoverElement");
  }
  resolvePath(e) {
    var t = e.indexOf("/");
    var o = e.substring(0, t);
    if (o === this.rootFolder.name) {
      var n = e.substring(t + 1);
      return this.rootFolder.resolvePath(n);
    }
  }
  unselectAll() {
    this.selectedItems.forEach((e) => {
      e.unselect();
    });
  }
  changeSelection(e, t, o) {
    if (!this.allowMultiSelect) {
      t = false;
      o = false;
    }
    if (o) {
      if (this.lastShiftKeyEndPoint) {
        var n = { state: false, unShiftMode: true };
        this.rootFolder.enumerateContent(false, (e) => {
          processShiftKey(e, this.selectedItem, this.lastShiftKeyEndPoint, n);
          return true;
        });
        this.selectedItem.select();
        this.lastShiftKeyEndPoint = undefined;
      }
      if (this.selectedItem) {
        var n = { state: false, unShiftMode: false };
        this.rootFolder.enumerateContent(false, (t) => {
          processShiftKey(t, this.selectedItem, e, n);
          return true;
        });
        this.lastShiftKeyEndPoint = e;
      }
    } else {
      this.lastShiftKeyEndPoint = undefined;
      if (!t) {
        this.unselectAll();
      }
      if (e) {
        e.select();
        if (!o) {
          this.selectedItem = e;
        }
      }
    }
    if (e && e.domObject)
      e.domObject.scrollIntoView({ block: "nearest", inline: "nearest" });
  }
  clear() {
    this.rootFolder.clear();
    this.selectedItem = undefined;
    this.selectedItems = [];
  }
  render() {
    this.sectionExpander = createDOMElement(
      undefined,
      "div",
      "panelHeaderIconLeft sectionExpanderIcon"
    );
    this.sectionExpander.onclick = () => {
      this.clearWatches();
    };
    this.sectionHeaderInner = createDOMElement(
      undefined,
      "div",
      "sectionHeaderInner",
      this.friendlyName
    );
    this.filterTextOuter = createDOMElement(
      undefined,
      "div",
      "filterTextOuter"
    );
    this.filterText = createDOMElement(
      this.filterTextOuter,
      "div",
      "filterText"
    );
    this.sectionRoot = createDOMElement(undefined, "div", "sectionRoot");
    this.sectionBody = createDOMElement(this.sectionRoot, "div", "sectionBody");
    var e = createDOMElement(this.sectionBody, "div", "tree");
    this.sectionRoot.ondblclick = (e) => {
      if (this.onDblClick) return this.onDblClick(e);
    };
    e.tabIndex = "0";
    e.onkeydown = (e) => this.onKeyDown(e);
    e.onkeypress = (e) => this.onKeyPress(e);
    this.sectionRoot.onkeydown = (e) => this.onKeyDown(e);
    this.sectionRoot.onkeypress = (e) => this.onKeyPress(e);
    this.rootFolder.domObject = e;
    assignToPanel(this, undefined, this.panelDiv);
  }
  onKeyPress(e) {
    if (document.getElementById("renameInput")) return true;
    debugger;
    var t = e.charCode;
    var o = String.fromCharCode(t);
    if (t == 32) {
      if (this.filterText.innerText.length == 0) return true;
    }
    if (t >= 32) {
      this.filterText.innerText += o;
      this.filterText.style.visibility = "visible";
      this.rootFolder.renderEntries();
    }
    e.stopPropagation();
  }
  onKeyDown(e) {
    e.stopPropagation();
    if (document.getElementById("renameInput")) return true;
    if (e.ctrlKey) {
      if (e.key == "ArrowUp") {
        this.sectionRoot.scroll(0, this.sectionRoot.scrollTop - 10);
      } else if (e.key == "ArrowDown") {
        this.sectionRoot.scroll(0, this.sectionRoot.scrollTop + 10);
      } else if (e.key == "a" || e.key == "A") {
        var t = undefined;
        this.rootFolder.enumerateContent(false, (e) => {
          if (e.domObject.style.display == "none") return true;
          this.changeSelection(e, true, false);
          return true;
        });
      }
    } else {
      if (e.key == "删除") {
        if (this.selectedItem) {
          if (this.onDeleteKey) this.onDeleteKey(e);
        }
      } else if (e.key == "ArrowLeft") {
        if (this.selectedItem) {
          if (this.selectedItem.entries && !this.selectedItem.isCollapsed) {
            let e = this.selectedItem;
            this.selectedItem.innerDiv.onclick(eCopy);
            this.changeSelection(e, false, false);
          } else {
            if (!this.selectedItem.parentFolder.isRootFolder)
              this.changeSelection(
                this.selectedItem.parentFolder,
                false,
                false
              );
          }
        }
      } else if (e.key == "ArrowRight") {
        if (this.selectedItem) {
          if (this.selectedItem.entries) {
            if (this.selectedItem.isCollapsed) {
              let t = this.selectedItem;
              let o = JSON.parse(JSON.stringify(e));
              o.button = 0;
              this.selectedItem.innerDiv.onclick(o);
              this.changeSelection(t, false, false);
            } else {
              this.changeSelection(
                this.selectedItem.entries[
                  Object.keys(this.selectedItem.entries)[0]
                ],
                false,
                false
              );
            }
          }
        }
      } else if (e.key == "ArrowUp") {
        if (this.selectedItem) {
          var t = undefined;
          this.rootFolder.enumerateContent(false, (o) => {
            if (o.domObject.style.display == "none") return true;
            if (o === this.selectedItem) {
              if (t) this.changeSelection(t, e.shiftKey, false);
              return false;
            }
            t = o;
            return true;
          });
        }
      } else if (e.key == "ArrowDown") {
        if (this.selectedItem) {
          var o = false;
          this.rootFolder.enumerateContent(false, (t) => {
            if (t.domObject.style.display == "none") return true;
            if (o) {
              this.changeSelection(t, e.shiftKey, false);
              return false;
            }
            if (t === this.selectedItem) {
              o = true;
            }
            return true;
          });
        }
      } else if (e.key == "Space") {
        if (this.selectedItem) {
          let t = JSON.parse(JSON.stringify(e));
          t.button = 0;
          this.selectedItem.innerDiv.onclick(t);
        }
      } else if (e.key == "Enter") {
        if (this.selectedItem) {
          let t = JSON.parse(JSON.stringify(e));
          t.button = 0;
          this.selectedItem.innerDiv.ondblclick(t);
        }
      } else if (e.key == "Escape") {
        if (this.filterText.innerText.length > 0) {
          this.filterText.innerText = "";
          this.filterText.style.visibility = "hidden";
          this.rootFolder.renderEntries();
        } else {
          this.changeSelection(undefined, false, false);
        }
      } else if (e.key == "Backspace") {
        if (this.filterText.innerText.length == 0) return;
        this.filterText.innerText = this.filterText.innerText.substring(
          0,
          this.filterText.innerText.length - 1
        );
        if (this.filterText.innerText.length == 0)
          this.filterText.style.visibility = "hidden";
        this.rootFolder.renderEntries();
      } else {
        return true;
      }
    }
    return false;
  }
}
const VIRTUALTREE_LISTOFFSET_CAPTION = 0;
const VIRTUALTREE_LISTOFFSET_NEXTNODE = 1;
const VIRTUALTREE_LISTOFFSET_PREVNODE = 2;
const VIRTUALTREE_LISTOFFSET_FIRSTCHILD = 3;
const VIRTUALTREE_LISTOFFSET_LASTCHILD = 4;
const VIRTUALTREE_LISTOFFSET_PARENTNODE = 5;
const VIRTUALTREE_LISTOFFSET_FLAGS = 6;
const VIRTUALTREE_LISTOFFSET_MAX = 7;
const VTREEFLAG_ISEXPANDED = 1;
const VTREEFLAG_GROUP1 = 2;
const VTREEFLAG_GROUP2 = 4;
class virtualTreeViewData {
  constructor(e, t) {
    this.controller = e;
    this.CountOfCustomProperties = t;
    this.CountOfFlatEntriesPerNode =
      VIRTUALTREE_LISTOFFSET_MAX + this.CountOfCustomProperties;
    this.isMultiUpdate = 0;
  }
  clear() {
    this.countOfVisibleNodes = 0;
    this.flatData = [];
    this.treeUniqueItemId = 1;
    this.countOfAllNodes = 0;
    this.deletedNodeIndexes = [];
    this.hideGroup1 = false;
    this.hideGroup2 = false;
    this.rootFolder = this.addSubNode();
    this.controller.onClearData();
  }
  setExpanded(e, t) {
    var o = this.flatData[e + VIRTUALTREE_LISTOFFSET_FLAGS];
    this.flatData[e + VIRTUALTREE_LISTOFFSET_FLAGS] =
      (o & ~VTREEFLAG_ISEXPANDED) | (t ? VTREEFLAG_ISEXPANDED : 0);
  }
  isExpanded(e) {
    var t = this.flatData[e + VIRTUALTREE_LISTOFFSET_FLAGS];
    return t & VTREEFLAG_ISEXPANDED;
  }
  setCustomData(e, t, o) {
    if (t <= this.CountOfCustomProperties) {
      this.flatData[e + VIRTUALTREE_LISTOFFSET_MAX + t] = o;
    } else {
      debugger;
    }
  }
  addSubNode(e, t, o, n, i, r, s, a) {
    var l;
    if (this.deletedNodeIndexes.length > 0) {
      l = this.deletedNodeIndexes.pop();
    } else {
      this.countOfAllNodes++;
      l = this.treeUniqueItemId;
      this.treeUniqueItemId +=
        VIRTUALTREE_LISTOFFSET_MAX + this.CountOfCustomProperties;
      this.flatData.length +=
        VIRTUALTREE_LISTOFFSET_MAX + this.CountOfCustomProperties;
    }
    if (o !== undefined && 1 <= this.CountOfCustomProperties) {
      this.flatData[l + VIRTUALTREE_LISTOFFSET_MAX] = o;
    }
    if (n !== undefined && 2 <= this.CountOfCustomProperties) {
      this.flatData[l + VIRTUALTREE_LISTOFFSET_MAX + 1] = n;
    }
    if (i !== undefined && 3 <= this.CountOfCustomProperties) {
      this.flatData[l + VIRTUALTREE_LISTOFFSET_MAX + 2] = i;
    }
    if (r !== undefined && 4 <= this.CountOfCustomProperties) {
      this.flatData[l + VIRTUALTREE_LISTOFFSET_MAX + 3] = r;
    }
    this.flatData[l + VIRTUALTREE_LISTOFFSET_FLAGS] =
      (s ? VTREEFLAG_GROUP1 : 0) ||
      (a ? VTREEFLAG_GROUP2 : 0) ||
      VTREEFLAG_ISEXPANDED;
    if (e) {
      this.flatData[l + VIRTUALTREE_LISTOFFSET_PARENTNODE] = e;
      this.flatData[l + VIRTUALTREE_LISTOFFSET_CAPTION] = t;
      var d = this.flatData[e + VIRTUALTREE_LISTOFFSET_LASTCHILD];
      if (d) {
        this.flatData[d + VIRTUALTREE_LISTOFFSET_NEXTNODE] = l;
        this.flatData[l + VIRTUALTREE_LISTOFFSET_PREVNODE] = d;
      } else {
        this.flatData[e + VIRTUALTREE_LISTOFFSET_FIRSTCHILD] = l;
      }
      this.flatData[e + VIRTUALTREE_LISTOFFSET_LASTCHILD] = l;
    }
    return l;
  }
  getNextVisibleNode2(e, t, o) {
    while (1) {
      e = this.getNextVisibleNode(e, t, o);
      if (e === undefined) return undefined;
      if (
        (this.hideGroup1 &&
          this.flatData[e + VIRTUALTREE_LISTOFFSET_FLAGS] & VTREEFLAG_GROUP1) ||
        (this.hideGroup2 &&
          this.flatData[e + VIRTUALTREE_LISTOFFSET_FLAGS] & VTREEFLAG_GROUP2)
      ) {
      } else {
        break;
      }
    }
    return e;
  }
  getNextVisibleNode(e, t, o) {
    if (!t) {
      if (
        o ||
        this.flatData[e + VIRTUALTREE_LISTOFFSET_FLAGS] & VTREEFLAG_ISEXPANDED
      ) {
        var n = this.flatData[e + VIRTUALTREE_LISTOFFSET_FIRSTCHILD];
        if (n) {
          return n;
        }
      }
    }
    var i = this.flatData[e + VIRTUALTREE_LISTOFFSET_NEXTNODE];
    if (i) {
      return i;
    }
    var r = this.flatData[e + VIRTUALTREE_LISTOFFSET_PARENTNODE];
    if (r) {
      if (r !== 1) {
        return this.getNextVisibleNode(r, true);
      }
    }
    return undefined;
  }
  deleteNode(e) {
    this.deleteNodeChildren(e);
    var t = this.flatData[e + VIRTUALTREE_LISTOFFSET_NEXTNODE];
    var o = this.flatData[e + VIRTUALTREE_LISTOFFSET_PREVNODE];
    if (t) {
      this.flatData[t + VIRTUALTREE_LISTOFFSET_PREVNODE] = o;
    }
    if (o) {
      this.flatData[o + VIRTUALTREE_LISTOFFSET_NEXTNODE] = t;
    }
    var n = this.flatData[e + VIRTUALTREE_LISTOFFSET_PARENTNODE];
    if (n) {
      var i = this.flatData[n + VIRTUALTREE_LISTOFFSET_FIRSTCHILD];
      var r = this.flatData[n + VIRTUALTREE_LISTOFFSET_LASTCHILD];
      if (i == e) {
        this.flatData[n + VIRTUALTREE_LISTOFFSET_FIRSTCHILD] = t;
      }
      if (r == e) {
        this.flatData[n + VIRTUALTREE_LISTOFFSET_LASTCHILD] = o;
      }
    }
    var s = e;
    var a = s + VIRTUALTREE_LISTOFFSET_MAX + this.CountOfCustomProperties;
    while (s < a) {
      this.flatData[s++] = 0;
    }
    this.deletedNodeIndexes.push(e);
  }
  deleteNodeChildren(e) {
    var t = this.flatData[e + VIRTUALTREE_LISTOFFSET_FIRSTCHILD];
    while (t) {
      var o = this.flatData[t + VIRTUALTREE_LISTOFFSET_NEXTNODE];
      this.deleteNode(t);
      t = o;
    }
  }
  updateVisibleNodesList() {
    if (this.isMultiUpdate) return;
    this.visibleNodesList = new Array(this.countOfAllNodes);
    var e = 0;
    var t = 1;
    while (t) {
      if (t !== 1) {
        this.visibleNodesList[e++] = t;
      }
      t = this.getNextVisibleNode2(t);
    }
    this.countOfVisibleNodes = e;
    this.controller.renderNow();
    if (this.controller.associatedToolWindows) {
      this.controller.associatedToolWindows.forEach((e) => {
        e.postMessageObject({ type: "treeChanged" });
      });
    }
  }
  startMultiUpdate() {
    this.isMultiUpdate++;
  }
  endMultiUpdate() {
    this.isMultiUpdate--;
    if (this.isMultiUpdate == 0) {
      this.updateVisibleNodesList();
    }
  }
  endMultiUpdateNoChanges() {
    this.isMultiUpdate--;
  }
  generateNodeInfo(e) {
    var t = this;
    return {
      getNodeIndex() {
        return e;
      },
      isExpanded() {
        return t.isExpanded(e);
      },
      getCaption() {
        return t.flatData[e + VIRTUALTREE_LISTOFFSET_CAPTION];
      },
      getCustomData(o) {
        return t.flatData[e + VIRTUALTREE_LISTOFFSET_MAX + o];
      },
      getParentNodeInfo() {
        var o = t.flatData[e + VIRTUALTREE_LISTOFFSET_PARENTNODE];
        return t.generateNodeInfo(o);
      },
      hasChildren() {
        var o = t.flatData[e + VIRTUALTREE_LISTOFFSET_FIRSTCHILD];
        return o !== undefined;
      },
      expand() {
        var o = t.flatData[e + VIRTUALTREE_LISTOFFSET_FLAGS];
        if ((o & VTREEFLAG_ISEXPANDED) == 0) {
          t.flatData[e + VIRTUALTREE_LISTOFFSET_FLAGS] =
            o ^ VTREEFLAG_ISEXPANDED;
        }
        t.updateVisibleNodesList();
      },
      collapse() {
        var o = t.flatData[e + VIRTUALTREE_LISTOFFSET_FLAGS];
        if (o & VTREEFLAG_ISEXPANDED) {
          t.flatData[e + VIRTUALTREE_LISTOFFSET_FLAGS] =
            o ^ VTREEFLAG_ISEXPANDED;
        }
        t.updateVisibleNodesList();
      },
    };
  }
  getHTMLNode(e) {
    let t = this.visibleNodesList[e];
    let o = this.generateNodeInfo(t);
    return this.controller.renderDomNode(o);
  }
  onClickNode(e) {
    let t = this.visibleNodesList[e];
    let o = this.generateNodeInfo(t);
    this.controller.onClickNode(o);
  }
  onRightClickNode(e, t, o) {
    let n = this.visibleNodesList[e];
    let i = this.generateNodeInfo(n);
    this.controller.onRightClickNode(i, t, o);
  }
  onDblClickNode(e) {
    let t = this.visibleNodesList[e];
    let o = this.generateNodeInfo(t);
    this.controller.onDblClickNode(o);
  }
  toggleExpanded(e) {
    let t = this.visibleNodesList[e];
    var o = this.flatData[t + VIRTUALTREE_LISTOFFSET_FLAGS];
    this.flatData[t + VIRTUALTREE_LISTOFFSET_FLAGS] = o ^ VTREEFLAG_ISEXPANDED;
    this.updateVisibleNodesList();
  }
}
class virtualTreeViewView {
  constructor(e, t) {
    this.data = new virtualTreeViewData(e, t);
  }
  increaseCache() {}
  updateLocalCache(e) {
    e();
  }
  getCountOfVisibleNodes() {
    return this.data.countOfVisibleNodes;
  }
  getHTMLNode(e) {
    return this.data.getHTMLNode(e);
  }
  onClickNode(e) {
    return this.data.onClickNode(e);
  }
  onRightClickNode(e, t, o) {
    return this.data.onRightClickNode(e, t, o);
  }
  onDblClickNode(e) {
    return this.data.onDblClickNode(e);
  }
  toggleExpanded(e) {
    this.data.toggleExpanded(e);
  }
}
var g_UpdateLocalCacheCallback = undefined;
var g_UpdateLocalCacheRequestId = 0;
class virtualTreeViewAdditionalView {
  constructor(e) {
    this.controller = e;
    this.cachedLocalNodesCount = 10;
  }
  increaseCache() {
    this.cachedLocalNodesCount += 10;
  }
  updateLocalCache(e) {
    g_UpdateLocalCacheCallback = e;
    g_UpdateLocalCacheRequestId++;
    window.chrome.webview.postMessage(
      JSON.stringify({
        toolWindowID: toolWindowID,
        type: "getNodesUISnapshot",
        visibleIndex: this.controller.visibleTopNodeIndex,
        requestCount: this.cachedLocalNodesCount,
        requestID: g_UpdateLocalCacheRequestId,
      })
    );
  }
  gotNodesUISnapshotResponse(e, t) {
    if (e === g_UpdateLocalCacheRequestId) {
      this.cachedResponse = t;
      if (g_UpdateLocalCacheCallback) {
        var o = g_UpdateLocalCacheCallback;
        g_UpdateLocalCacheCallback = undefined;
        o();
      }
    }
  }
  getCountOfVisibleNodes() {
    return this.cachedResponse.totalVisibleNodesCount;
  }
  getHTMLNode(e) {
    if (
      e >=
      this.cachedResponse.visibleIndexStart +
        this.cachedResponse.htmlNodes.length
    ) {
      return undefined;
    }
    return this.cachedResponse.htmlNodes[
      e - this.cachedResponse.visibleIndexStart
    ];
  }
  onClickNode(e) {
    window.chrome.webview.postMessage(
      JSON.stringify({
        toolWindowID: toolWindowID,
        type: "clickedNode",
        visibleIndex: e,
      })
    );
  }
  onRightClickNode(e, t, o) {
    window.chrome.webview.postMessage(
      JSON.stringify({
        toolWindowID: toolWindowID,
        type: "rightClickedNode",
        visibleIndex: e,
        clientX: t,
        clientY: o,
      })
    );
  }
  onDblClickNode(e) {
    window.chrome.webview.postMessage(
      JSON.stringify({
        toolWindowID: toolWindowID,
        type: "dblClickedNode",
        visibleIndex: e,
      })
    );
  }
  toggleExpanded(e) {
    window.chrome.webview.postMessage(
      JSON.stringify({
        toolWindowID: toolWindowID,
        type: "toggleExpanded",
        visibleIndex: e,
      })
    );
  }
}
class virtualTreeView {
  constructor(e, t, o, n, i, r, s) {
    if (s) {
      this.view = new virtualTreeViewAdditionalView(this);
    } else {
      this.associatedToolWindows = [];
      this.view = new virtualTreeViewView(this, i);
      this.view.data.clear();
    }
    this.panelDiv = e;
    this.rootSelector = document.querySelector(":root");
    this.name = o;
    this.allowMultiSelect = n;
    this.friendlyName = t;
    this.cssVarsPrefix = r;
    this.cached_CountOfVisibleNodes = 0;
    this.visibleTopNodeIndex = 0;
  }
  getNodesUISnapshot(e, t) {
    var o = {
      htmlNodes: [],
      totalVisibleNodesCount: this.view.data.countOfVisibleNodes,
      visibleIndexStart: 0,
    };
    var n = e;
    if (
      n >= this.view.data.countOfVisibleNodes &&
      this.view.data.countOfVisibleNodes > 0
    ) {
      n = this.view.data.countOfVisibleNodes - 1;
    }
    if (n + t > this.view.data.countOfVisibleNodes) {
      t = this.view.data.countOfVisibleNodes - n;
    }
    if (t < 0) t = 0;
    var i = 0;
    while (i < t) {
      o.htmlNodes[i] = this.view.getHTMLNode(n + i);
      i++;
    }
    o.visibleIndexStart = n;
    return o;
  }
  onClearData() {
    if (this.sectionRoot) this.view.data.updateVisibleNodesList();
  }
  scrollY(e) {
    e /= 100;
    if (e > 0) {
      while (e > 0) {
        var t = this.visibleTopNodeIndex + 1;
        if (t >= this.cached_CountOfVisibleNodes) break;
        this.visibleTopNodeIndex = t;
        e -= 1;
      }
    } else {
      while (e < 0) {
        var o = this.visibleTopNodeIndex - 1;
        if (o < 0) break;
        this.visibleTopNodeIndex = o;
        e += 1;
      }
    }
    this.renderNow();
  }
  scrollToPosition(e) {
    var t = e / this.scrollBarVContainer.offsetHeight;
    var o = Math.trunc(this.cached_CountOfVisibleNodes * t);
    if (o < 0) o = 0;
    if (o > this.countOfVisibleNodes - 1) o = this.countOfVisibleNodes - 1;
    this.visibleTopNodeIndex = o;
    this.renderNow();
  }
  panelResized() {
    this.renderNow();
  }
  finishedInit() {
    if (this.panelDiv.isToolWindow) {
      var e = createDOMElement(
        this.sectionHeader,
        "div",
        "panelHeaderIcon closeIcon"
      );
      e.onclick = (e) => {
        this.panelDiv.closeButtonClicked();
      };
    }
  }
  init() {
    this.sectionExpander = createDOMElement(
      undefined,
      "div",
      "panelHeaderIconLeft sectionExpanderIcon"
    );
    this.sectionHeaderInner = createDOMElement(
      undefined,
      "div",
      "sectionHeaderInner",
      this.friendlyName
    );
    this.filterTextOuter = createDOMElement(
      undefined,
      "div",
      "filterTextOuter"
    );
    this.filterText = createDOMElement(
      this.filterTextOuter,
      "div",
      "filterText"
    );
    this.sectionRoot = createDOMElement(
      undefined,
      "div",
      "sectionRootNoScroll"
    );
    this.sectionBody = createDOMElement(this.sectionRoot, "div", "sectionBody");
    this.scrollBarVContainer = createDOMElement(
      this.sectionRoot,
      "div",
      "scrollBarVContainer" + this.friendlyName
    );
    this.scrollBarV = createDOMElement(
      this.scrollBarVContainer,
      "div",
      "scrollBarV" + this.friendlyName
    );
    this.treeDiv = createDOMElement(
      this.sectionBody,
      "div",
      "tree treeCustomScroll"
    );
    new ResizeObserver(() => this.panelResized()).observe(this.sectionRoot);
    this.scrollBarVContainer.addEventListener(
      "mousedown",
      (e) => {
        this.scrollToPosition(e.layerY - this.scrollBarVContainer.offsetTop);
      },
      false
    );
    this.scrollBarV.addEventListener(
      "mousedown",
      (e) => {
        this.mouseDownListener = (e) => {
          var { top: t } = this.scrollBarVContainer.getBoundingClientRect();
          this.scrollToPosition(e.pageY - t);
          e.stopPropagation();
        };
        this.mouseUpListener = () => {
          document.removeEventListener("mousemove", this.mouseDownListener);
          document.removeEventListener("mouseup", this.mouseUpListener);
        };
        document.addEventListener("mousemove", this.mouseDownListener, false);
        document.addEventListener("mouseup", this.mouseUpListener, false);
        e.stopPropagation();
      },
      false
    );
    this.sectionRoot.addEventListener(
      "wheel",
      (e) => {
        this.scrollY(e.deltaY);
        e.preventDefault();
      },
      false
    );
    assignToPanel(this, undefined, this.panelDiv);
    this.allocatedDomNodes = createDOMElement(this.treeDiv, "div");
  }
  renderNow() {
    this.view.updateLocalCache(() => {
      var e = this.allocatedDomNodes;
      const t = this.sectionRoot.getBoundingClientRect();
      if (t.bottom === 0) {
        setTimeout(() => this.renderNow(), 1e3);
        return;
      }
      var o = this.visibleTopNodeIndex;
      var n = this.view.getCountOfVisibleNodes();
      this.cached_CountOfVisibleNodes = n;
      if (o >= n && n > 0) {
        o = n - 1;
      }
      this.rootSelector.style.setProperty(
        this.cssVarsPrefix + "ScrollPosition",
        o
      );
      this.rootSelector.style.setProperty(this.cssVarsPrefix + "ScrollMax", n);
      this.rootSelector.style.setProperty(
        this.cssVarsPrefix + "ScrollOpacity",
        1
      );
      var i = false;
      while (o < n) {
        var r = this.view.getHTMLNode(o);
        if (r === undefined) {
          this.view.increaseCache();
          this.renderNow();
          return;
        }
        e.innerHTML = r;
        const { bottom: n } = e.getBoundingClientRect();
        if (!e.nextDomNode) {
          e.nextDomNode = createDOMElement(this.treeDiv, "div");
          let t = e;
          e.onclick = (e) => {
            this.view.onClickNode(t.nodeVisibleIndex);
          };
          e.oncontextmenu = (e) => {
            this.view.onRightClickNode(
              t.nodeVisibleIndex,
              e.clientX,
              e.clientY
            );
          };
          e.ondblclick = (e) => {
            this.view.onDblClickNode(t.nodeVisibleIndex);
          };
        }
        e.nodeVisibleIndex = o++;
        e = e.nextDomNode;
        if (n > t.bottom) {
          i = true;
          break;
        }
      }
      if (!i) {
        if (this.visibleTopNodeIndex === 0) {
          this.rootSelector.style.setProperty(
            this.cssVarsPrefix + "ScrollOpacity",
            0
          );
        }
      }
      while (e) {
        e.innerHTML = "";
        e = e.nextDomNode;
      }
    });
  }
}
var startDropZone = undefined;
var startDropZoneItem = undefined;
var currentDropZone = undefined;
var currentDropZoneItem = undefined;
function onDragTreeItemStart(e, t, o) {
  startDropZone = t;
  startDropZoneItem = o;
  currentDragType = DRAG_TREE_NODE;
  hideTooltipNow();
  o.tree.hideHoverElement();
  if (!o.isSelected) {
    o.tree.changeSelection(o, false, false);
  }
  e.dataTransfer.setData("text/plain", o.tree.getSelectedItemsIds().join(";"));
}
function onDragTreeItemDropped(e) {
  if (currentDragType !== DRAG_TREE_NODE) return;
  e.preventDefault();
  if (currentDropZone != startDropZone) {
    var t = e.dataTransfer.getData("text/plain");
    var o = [];
    t.split(";").forEach((e) => {
      o.push(currentDropZoneItem.tree.resolvePath("twinbasic:" + e));
    });
    currentDropZoneItem.tree.onDragDropped(o, currentDropZoneItem);
  }
}
function onDragTreeItemHover(e, t, o) {
  if (currentDragType !== DRAG_TREE_NODE) return;
  e.preventDefault();
  if (o.tree !== startDropZoneItem.tree) {
    e.dataTransfer.dropEffect = "none";
    return;
  }
  e.dataTransfer.dropEffect = "move";
  if (currentDropZone != t) {
    if (currentDropZone) {
      currentDropZone.classList.remove("folderDropZone");
      if (currentDropZone.additionalDropZone)
        currentDropZone.additionalDropZone.classList.remove("folderDropZone");
      currentDropZone = undefined;
    }
    if (
      t != startDropZone &&
      t != startDropZone.additionalDropZone &&
      t.additionalDropZone != startDropZone.additionalDropZone &&
      t.additionalDropZone != startDropZone
    ) {
      t.classList.add("folderDropZone");
      if (t.additionalDropZone)
        t.additionalDropZone.classList.add("folderDropZone");
    }
    currentDropZone = t;
    currentDropZoneItem = o;
  }
}
function onDragTreeItemEnd(e, t, o) {
  currentDragType = undefined;
  if (currentDropZone) {
    currentDropZone.classList.remove("folderDropZone");
    if (currentDropZone.additionalDropZone)
      currentDropZone.additionalDropZone.classList.remove("folderDropZone");
    currentDropZone = undefined;
  }
  o.tree.unhideHoverElement();
}
function toggleFolder(e) {
  var t = e.target.parentElement.treeNode;
  t.isCollapsed = !t.isCollapsed;
  t.render(undefined);
}
class treeViewFolder {
  constructor(e, t, o, n, i, r, s, a) {
    this.tree = e;
    this.parentFolder = t;
    this.folderLevel = o;
    this.isCollapsed = s !== undefined ? s : i ? false : true;
    this.entries = {};
    this.domObject = undefined;
    this.isRootFolder = i;
    this.name = n;
    this.isSelected = false;
    this.displayName = r;
    this.isFolder = true;
    this.sort = true;
    this.extraInfo = a;
  }
  select() {
    if (!this.isSelected) {
      if (this.innerDiv) this.innerDiv.classList.add("treeItemSelected");
      this.tree.selectedItems.push(this);
      this.isSelected = true;
    }
  }
  unselect() {
    if (this.isSelected) {
      if (this.innerDiv) this.innerDiv.classList.remove("treeItemSelected");
      this.tree.selectedItems = this.tree.selectedItems.filter(
        (e) => e != this
      );
      this.isSelected = false;
    }
  }
  getFullPath() {
    return this.isRootFolder
      ? ""
      : this.parentFolder.getFullPath() + "/" + this.name;
  }
  getFirstItem() {
    if (Object.keys(this.entries).length > 0) {
      return this.entries[Object.keys(this.entries)[0]];
    }
    return undefined;
  }
  resolvePath(e) {
    var t = e.indexOf("/");
    if (t == e.length - 1) {
      e = e.substring(0, e.length - 1);
      t = -1;
    }
    if (t != -1) {
      var o = e.substring(0, t);
      if (!this.tree.caseSensitiveEntries) o = o.toLowerCase();
      var n = this.entries[o];
      if (n) {
        return n.resolvePath(e.substring(t + 1));
      }
    } else {
      if (!this.tree.caseSensitiveEntries) e = e.toLowerCase();
      return this.entries[e];
    }
  }
  removeEntry(e) {
    var t = e.name;
    if (!this.tree.caseSensitiveEntries) t = t.toLowerCase();
    if (this.entries[t] === e) {
      delete this.entries[t];
      this.render(undefined);
    }
  }
  expand() {
    this.isCollapsed = false;
    this.render(undefined);
  }
  onClick(e) {
    if (this.isRenaming) return;
    if (
      this.tree.autoExpandOnSelect &&
      !e.dontToggle &&
      !e.shiftKey &&
      !e.ctrlKey
    )
      this.isCollapsed = !this.isCollapsed;
    this.render(undefined);
    this.tree.changeSelection(this, e.ctrlKey, e.shiftKey);
    if (e.button == 0 && this.tree.onClickFolder)
      return this.tree.onClickFolder(e, this);
  }
  onDblClick(e) {
    if (this.isRenaming) return;
    if (e.button == 0 && this.tree.onDblClickFolder)
      return this.tree.onDblClickFolder(e, this);
  }
  addFolder(e, t, o, n) {
    var i = new treeViewFolder(
      this.tree,
      this,
      this.folderLevel + 1,
      e,
      false,
      t,
      undefined,
      n
    );
    if (o) i.isCollapsed = false;
    if (this.tree.autoHideEntriesBeginningWithDot) {
      if (e.substr(0, 1) === ".") {
        i.isHidden = true;
      }
    }
    if (!this.tree.caseSensitiveEntries) e = e.toLowerCase();
    this.entries[e] = i;
    if (!this.muteRendering) this.renderEntries();
    return i;
  }
  adoptItem(e) {
    this.entries[e.name] = e;
    if (!this.muteRendering) this.renderEntries();
  }
  addItem(e, t, o, n, i, r, s) {
    var a = new treeViewItem(
      this.tree,
      this,
      this.folderLevel + 1,
      e,
      t,
      o,
      n,
      i,
      r,
      s
    );
    if (this.tree.autoHideEntriesBeginningWithDot) {
      if (e.substr(0, 1) === ".") {
        a.isHidden = true;
      }
    }
    if (!this.tree.caseSensitiveEntries) e = e.toLowerCase();
    this.entries[e] = a;
    if (!this.muteRendering) this.renderEntries();
    return a;
  }
  addItemCustom(e, t, o, n) {
    var i = new treeViewItem(this.tree, this, this.folderLevel + 1, e, n);
    this.entries[e] = i;
    i.customRenderFunc = t;
    i.customRenderData = o;
    if (!this.muteRendering) this.renderEntries();
    return i;
  }
  addFolderCustom(e, t, o, n) {
    var i = new treeViewFolder(
      this.tree,
      this,
      this.folderLevel + 1,
      e,
      false,
      undefined,
      n
    );
    this.entries[e] = i;
    i.customRenderFunc = t;
    i.customRenderData = o;
    if (!this.muteRendering) this.renderEntries();
    return i;
  }
  clear() {
    var e;
    for (const e in this.entries) {
      var t = this.entries[e];
      if (t.domObject) t.domObject.parentElement.removeChild(t.domObject);
      delete this.entries[e];
    }
  }
  removeItem(e) {
    var t = e.name;
    if (!this.tree.caseSensitiveEntries) t = t.toLowerCase();
    delete this.entries[t];
    e.domObject.parentElement.removeChild(e.domObject);
  }
  render(e) {
    if (e) {
      this.domObject = createDOMElement(e, "div", "treeItem");
    } else {
      if (!this.domObject) return;
      this.domObject.innerText = "";
      if (this.innerDiv.parentNode)
        this.innerDiv.parentNode.removeChild(this.innerDiv);
      delete this.innerDiv;
    }
    this.innerDiv = createDOMElement(
      this.domObject,
      "div",
      "treeItemInner",
      this.customRenderFunc
        ? ""
        : this.displayName
        ? this.displayName
        : this.name
    );
    if (this.cachedDiagnostics_childErrorCount) {
      this.innerDiv.classList.add("error");
    } else if (this.cachedDiagnostics_childWarningCount) {
      this.innerDiv.classList.add("warning");
    }
    this.innerDiv.treeNode = this;
    this.innerDiv.style.paddingLeft =
      20 * this.folderLevel + this.tree.itemPaddingLeft + "px";
    if (this.isSelected) this.innerDiv.classList.add("treeItemSelected");
    var t = this.isCollapsed
      ? "treeNodeIcon iconExpand14"
      : "treeNodeIcon iconCollapse14";
    var o = this.tree.showFolderIcons ? "<div class='folderIcon'></div>" : "";
    var n = this.tree.autoExpandOnSelect
      ? ""
      : " onclick='toggleFolder(event)'";
    if (this.customRenderFunc) {
      this.customRenderFunc(this);
    }
    if (!this.isRenaming) {
      this.innerDiv.innerHTML =
        "<div class='" +
        t +
        "'" +
        n +
        "></div>" +
        o +
        "<div class='itemNode" +
        (this.tree.needsFlexNodes ? " itemNodeFlex" : "") +
        "'>" +
        this.innerDiv.innerHTML +
        "</div>" +
        (this.extraInfo
          ? "<div class='extraInfo'>" + this.extraInfo + "</div>"
          : "");
    } else {
      this.innerDiv.innerHTML =
        "<div class='" +
        t +
        "'></div>" +
        o +
        "<input id='renameInput' type='text' class='text' value='" +
        this.innerDiv.innerText +
        "'/>";
      this.tree.activateRenameHandling(this);
    }
    this.innerDiv.draggable = true;
    this.innerDiv.ondragstart = (e) => {
      onDragTreeItemStart(e, this.domObject, this);
    };
    this.innerDiv.ondragover = (e) => {
      onDragTreeItemHover(e, this.domObject, this);
    };
    this.innerDiv.ondragend = (e) => {
      onDragTreeItemEnd(e, this.domObject, this);
    };
    this.innerDiv.ondrop = (e) => {
      onDragTreeItemDropped(e);
    };
    this.innerDiv.oncontextmenu = (e) => this.tree.onRightClickFolder(e, this);
    this.innerDiv.onclick = (e) => {
      if (e.button == 0) return this.onClick(e, this);
    };
    this.innerDiv.ondblclick = (e) => {
      if (e.button == 0) return this.onDblClick(e, this);
    };
    if (this.tree.showTooltips) {
      this.innerDiv.onmouseenter = (e) => {
        var t = this.toolTip;
        if (this.tree.onTooltip) t = this.tree.onTooltip(e, this);
        setTooltip(t, e.clientX + 10, e.clientY + 10);
      };
      this.innerDiv.onmouseleave = (e) => {
        unsetTooltip(true);
      };
      this.renderEntries();
    }
  }
  unrender() {
    delete this.domObject;
  }
  getSortedEntries() {
    var e = this.entries;
    if (this.sort) {
      e = sortObjectByKeys(this.entries, (e, t) => {
        var o = this.entries[e].isFolder;
        var n = this.entries[t].isFolder;
        if (o === n) {
          if (e < t) return -1;
          if (e > t) return 1;
        } else {
          if (o) return -1;
          if (n) return 1;
        }
        return 0;
      });
    }
    return e;
  }
  enumerateContent(e, t) {
    if (!this.isRootFolder && !t(this)) return false;
    if (e || !this.isCollapsed) {
      var o = this.getSortedEntries();
      for (const n in o) {
        if (!o[n].enumerateContent(e, t)) return false;
      }
    }
    return true;
  }
  renderEntries() {
    doLayoutChanges(() => {
      if (this.emptyDiv) {
        if (this.emptyDiv.parentNode)
          this.emptyDiv.parentNode.removeChild(this.emptyDiv);
        delete this.emptyDiv;
        this.emptyDiv = undefined;
      }
      if (this.domEntries !== undefined) {
        if (this.domEntries.parentNode)
          this.domEntries.parentNode.removeChild(this.domEntries);
        delete this.domEntries;
        this.domEntries = undefined;
        for (const e in this.entries) {
          this.entries[e].unrender();
        }
      }
      if (this.isCollapsed) {
      } else {
        this.domEntries = createDOMElement(
          this.domObject,
          "div",
          "treeExpandedGroup " + this.tree.additionalFolderClassNames
        );
        this.domEntries.additionalDropZone = this.domObject;
        this.domObject.additionalDropZone = this.domEntries;
        var e = this.getSortedEntries();
        var t = 0;
        var o = this.tree.showHiddenEntries;
        for (const i in e) {
          var n = this.entries[i];
          if (o || !n.isHidden) {
            n.render(this.domEntries);
            t++;
          }
        }
        if (domCount) {
        }
        if (t === 0 && this.tree.emptyFolderText.length > 0) {
          this.emptyDiv = createDOMElement(
            this.domObject,
            "div",
            "treeItemInner treeItemInnerNoHover treeItemEmpty"
          );
          this.emptyDiv.style.paddingLeft =
            20 * this.folderLevel + this.tree.itemPaddingLeft + "px";
          this.emptyDiv.innerHTML =
            "<div class='noicon'></div><div class='noicon2'></div><div class='text'><i>" +
            this.tree.emptyFolderText +
            "</i></div><div class='marker'></div>";
          this.emptyDiv.ondragover = (e) => {
            onDragTreeItemHover(e, this.domObject, this);
          };
          this.emptyDiv.ondrop = (e) => {
            onDragTreeItemDropped(e);
          };
        }
      }
    });
  }
}
var domCount = 0;
class treeViewItem {
  constructor(e, t, o, n, i, r, s, a, l, d) {
    this.tree = e;
    this.parentFolder = t;
    this.folderLevel = o;
    this.name = n;
    this.iconClass = i;
    this.treeItemClass = r;
    this.toolTip = s;
    this.isSelected = false;
    this.displayName = a;
    this.isRenaming = l;
    this.extraInfo = d;
    if (!s) this.toolTip = this.getFullPath();
  }
  select() {
    if (!this.isSelected) {
      if (this.innerDiv) this.innerDiv.classList.add("treeItemSelected");
      this.tree.selectedItems.push(this);
      this.isSelected = true;
    }
  }
  unselect() {
    if (this.isSelected) {
      if (this.innerDiv) this.innerDiv.classList.remove("treeItemSelected");
      this.tree.selectedItems = this.tree.selectedItems.filter(
        (e) => e != this
      );
      this.isSelected = false;
    }
  }
  getFullPath() {
    return this.parentFolder.getFullPath() + "/" + this.name;
  }
  render(e) {
    if (e) {
      this.domObject = createDOMElement(e, "div", "treeItem");
    } else {
      if (!this.domObject) return;
      this.domObject.innerText = "";
      if (this.innerDiv.parentNode)
        this.innerDiv.parentNode.removeChild(this.innerDiv);
      delete this.innerDiv;
    }
    if (this.name && this.name.length > 0) {
      var t = this.name.indexOf("␞");
      if (t != -1) {
        this.displayName = this.name.substring(0, t);
      }
    }
    var o = "treeItemInner " + (this.treeItemClass ? this.treeItemClass : "");
    this.innerDiv = createDOMElement(
      this.domObject,
      "div",
      o,
      this.customRenderFunc
        ? ""
        : this.displayName
        ? this.displayName
        : this.name
    );
    if (this.isSelected) this.innerDiv.classList.add("treeItemSelected");
    if (this.customRenderFunc) {
      this.customRenderFunc(this);
    }
    var n = "";
    if (this.tree.isSimpleList) {
      this.innerDiv.style.paddingLeft = this.tree.itemPaddingLeft + "px";
    } else {
      this.innerDiv.style.paddingLeft =
        20 * this.folderLevel + this.tree.itemPaddingLeft + "px";
      if (this.tree.showFolderIcons) {
        n = "<div class='noicon'></div>";
      }
    }
    var i = this.tree.showItemIcons
      ? "<div class='" +
        (this.iconClass ? this.iconClass : "noicon2") +
        "'></div>"
      : "";
    if (!this.isRenaming) {
      this.innerDiv.innerHTML =
        n +
        i +
        "<div class='itemNode" +
        (this.tree.needsFlexNodes ? " itemNodeFlex" : "") +
        "'>" +
        this.innerDiv.innerHTML +
        "</div>" +
        (this.extraInfo
          ? "<div class='extraInfo'>" + this.extraInfo + "</div>"
          : "") +
        "<div class='marker'></div>";
    } else {
      var r = this.name ? this.name : this.innerDiv.innerText;
      this.innerDiv.innerHTML =
        n +
        i +
        "<input id='renameInput' type='text' class='text' value='" +
        this.innerDiv.innerText +
        "'/><div class='marker'></div>";
      document.getElementById("renameInput").value = r;
      this.tree.activateRenameHandling(this);
    }
    if (e) {
      this.domObject.draggable = true;
      this.domObject.ondragstart = (t) => {
        onDragTreeItemStart(t, e, this);
      };
      this.domObject.ondragover = (t) => {
        onDragTreeItemHover(t, e, this.parentFolder);
      };
      this.domObject.ondragend = (t) => {
        onDragTreeItemEnd(t, e, this);
      };
      this.domObject.ondrop = (e) => {
        onDragTreeItemDropped(e);
      };
    }
    if (this.tree.filterText.innerText.length > 0) {
      if (
        !this.name
          .toLowerCase()
          .includes(this.tree.filterText.innerText.toLowerCase())
      ) {
        this.domObject.style.display = "none";
      }
    }
    this.innerDiv.oncontextmenu = (e) => this.tree.onRightClickItem(e, this);
    this.innerDiv.onclick = (e) => {
      if (e.button == 0 && this.tree.onClickItem)
        return this.tree.onClickItem(e, this);
    };
    this.innerDiv.ondblclick = (e) => {
      if (e.button == 0 && this.tree.onDblClickItem)
        return this.tree.onDblClickItem(e, this);
    };
    if (this.tree.showTooltips) {
      this.innerDiv.onmouseenter = (e) => {
        var t = this.toolTip;
        if (this.tree.onTooltip) t = this.tree.onTooltip(e, this);
        setTooltip(t, e.clientX + 10, e.clientY + 10);
      };
      this.innerDiv.onmousemove = (e) => {
        setTooltipPosition(e.clientX + 10, e.clientY + 10);
      };
      this.innerDiv.onmouseleave = (e) => {
        unsetTooltip(true);
      };
    }
    if (this.isHidden) {
      this.domObject.style.display = "none";
    }
  }
  unrender() {
    delete this.domObject;
  }
  enumerateContent(e, t) {
    if (!t(this)) return false;
    return true;
  }
}
var variablesPanel;
function initVariablesPanel() {}
function onVariableDblClick(e, t) {
  var o = t.customRenderData;
  var n = t.parentFolder.variablesReference;
  if (!n && t.parentFolder.customRenderData)
    n = t.parentFolder.customRenderData.variablesReference;
  t.innerDiv.innerHTML =
    "<input id='renameInput' type='text' class='text' value='" +
    o.value +
    "' spellcheck='false'/>";
  setTimeout(() => {
    var e = document.getElementById("renameInput");
    e.onblur = () => {
      if (!e.cancelled) {
        debugSocket.request(
          "setVariable",
          { variablesReference: n, name: o.name, value: e.value },
          (e) => {
            if (e.success) {
              t.customRenderData = {
                name: o.name,
                variablesReference: e.body.variablesReference,
                value: e.body.value,
                type: e.body.type,
              };
              t.render(undefined);
            }
          }
        );
      }
      t.isRenaming = false;
      t.render();
    };
    e.select();
    e.focus();
    e.scrollIntoView({ block: "center" });
    e.onclick = (e) => {
      e.stopPropagation();
      return false;
    };
    e.ondblclick = (e) => {
      e.stopPropagation();
      return false;
    };
    e.onkeydown = (t) => {
      if (t.key == "Enter") {
        e.blur();
        t.stopPropagation();
      }
      if (t.key == "Escape") {
        e.cancelled = true;
        e.value = "";
        e.blur();
        t.stopPropagation();
      }
    };
  }, 0);
  return false;
}
function variableRenderComplexNode(e) {
  var t = e.innerDiv;
  var o = createDOMElement(t, "div", "variableName");
  var n = createDOMElement(t, "div", "variableValue");
  var i = createDOMElement(t, "div", "variableType");
  var r = e.customRenderData;
  o.innerText = r.name + (r.value.length ? ":" : "");
  n.innerText = r.value;
  i.innerText = r.type;
  if (!e.isCollapsed) {
    variablesPanel.expandedCache[e.getFullPath()] = true;
    if (!e.queried) {
      e.queried = true;
      if (isDebugMode)
        debugOutputLine(
          "requesting variables for reference " + r.variablesReference
        );
      var s = performance.now();
      debugSocket.request(
        "variables",
        { variablesReference: r.variablesReference },
        (t) => {
          var o = performance.now();
          if (isDebugMode)
            debugOutputLine(
              "requesting variables for reference " +
                r.variablesReference +
                "... done (taken " +
                (o - s) +
                ")"
            );
          variablesPanel.syncVariablesToNode(t, e);
        }
      );
    }
  } else {
    delete variablesPanel.expandedCache[e.getFullPath()];
  }
}
function variableRenderNode(e) {
  var t = e.innerDiv;
  var o = createDOMElement(t, "div", "variableName");
  var n = createDOMElement(t, "div", "variableValue");
  var i = createDOMElement(t, "div", "variableType");
  var r = e.customRenderData;
  o.innerText = r.name + (r.value.length ? ":" : "");
  n.innerText = r.value;
  i.innerText = r.type;
}
class _VariablesPanel {
  constructor(e, t, o, n, i, r) {
    this.expandedCache = {};
    this.tree = new treeView(e, "变量", "variables:", false, 5, false);
    this.tree.render();
    this.selectedEditorNode = undefined;
    this.tree.showFolderIcons = false;
    this.tree.showItemIcons = false;
    this.tree.onDblClickItem = onVariableDblClick;
    this.tree.emptyFolderText = "";
    this.tree.rootFolder.sort = true;
    this.tree.needsFlexNodes = true;
  }
  syncVariableToNode(e, t) {
    var o = t.getFullPath();
    if (e.variablesReference) {
      var n = this.expandedCache[o + "/" + e.name];
      var i = t.addFolderCustom(
        e.name,
        variableRenderComplexNode,
        e,
        n ? false : true
      );
      i.sort = true;
    } else {
      t.addItemCustom(e.name, variableRenderNode, e);
      if (e.name.indexOf("(") === 0) {
        t.sort = false;
      }
    }
  }
  syncVariablesToNode(e, t) {
    t.muteRendering = true;
    e.body.variables.forEach((e) => {
      this.syncVariableToNode(e, t);
    });
    t.emptyDiv = undefined;
    t.muteRendering = false;
    t.renderEntries();
  }
  syncVariablesPanelToStackFrame(e) {
    if (e && !e.syncing) {
      e.syncing = true;
      if (isDebugMode)
        debugOutputLine("requesting scopes for stackframe id " + e.id);
      var t = performance.now();
      debugSocket.request("scopes", { frameId: e.id }, (o) => {
        var n = performance.now();
        if (isDebugMode)
          debugOutputLine(
            "requesting scopes for stackframe id " +
              e.id +
              "... done (taken " +
              (n - t) +
              ")"
          );
        this.tree.rootFolder.muteRendering = true;
        o.body.scopes.forEach((e) => {
          e.value = "";
          e.type = "";
          this.syncVariableToNode(e, this.tree.rootFolder);
        });
        this.tree.rootFolder.muteRendering = false;
        this.tree.rootFolder.renderEntries();
        e.syncing = false;
      });
    }
  }
  clearVariablesInfo() {
    this.tree.clear();
  }
}
function createVariablesPanel(e) {
  if (variablesPanel) return variablesPanel;
  variablesPanel = new _VariablesPanel(e);
}
var watchPanel;
function initWatchPanel() {}
function onDeleteKey(e) {
  var t = watchPanel.tree.selectedItem;
  watchPanel.tree.rootFolder.removeItem(t);
}
function onWatchDblClick(e, t) {
  t.innerDiv.innerHTML =
    "<input id='renameInput' type='text' class='text' value='" +
    t.name +
    "' placeholder='添加表达式到监视...' spellcheck='false'/>";
  setTimeout(() => {
    var e = document.getElementById("renameInput");
    e.onblur = () => {
      var o = e.cancelled ? undefined : e.value;
      if (o !== undefined) {
        watchPanel.tree.rootFolder.removeItem(t);
        if (e.value.length) addNewWatchExpression(e.value);
      }
      t.isRenaming = false;
      t.render();
    };
    e.select();
    e.focus();
    e.scrollIntoView({ block: "center" });
    e.onclick = (e) => {
      e.stopPropagation();
      return false;
    };
    e.ondblclick = (e) => {
      e.stopPropagation();
      return false;
    };
    e.onkeydown = (t) => {
      if (t.key == "Enter") {
        e.onblur();
        t.stopPropagation();
      }
      if (t.key == "Escape") {
        e.cancelled = true;
        e.value = "";
        e.onblur();
        t.stopPropagation();
      }
    };
  }, 0);
  return false;
}
function addNewWatchExpression(e) {
  if (e && e.length > 0) {
    var t = watchPanel.expandedCache["/" + e];
    watchPanel.tree.rootFolder.addFolderCustom(
      e,
      watchRenderComplexNode,
      undefined,
      t ? false : true
    );
    watchPanel.evaluateWatch(e);
  }
}
function watches_onTreeDblClick(e) {
  e.stopPropagation();
  var t = watchPanel.tree.rootFolder.addItem(
    "",
    undefined,
    undefined,
    undefined,
    undefined,
    true
  );
  t.rename = (e, o) => {
    try {
      watchPanel.tree.rootFolder.removeItem(t);
    } catch (e) {}
    if (o && o.length > 0) addNewWatchExpression(o);
  };
  var o = document.getElementById("renameInput");
  o.placeholder = "添加表达式到监视...";
  o.onclick = (e) => {
    e.stopPropagation();
    return false;
  };
  o.ondblclick = (e) => {
    e.stopPropagation();
    return false;
  };
  t.domObject.focus();
  t.domObject.scrollIntoView({ block: "center" });
}
function watchRenderComplexNode(e) {
  var t = createDOMElement(e.innerDiv, "div", "variableName");
  var o = createDOMElement(e.innerDiv, "div", "variableValue");
  var n = createDOMElement(e.innerDiv, "div", "variableType");
  var i = e.customRenderData;
  t.innerText = e.name + ":";
  if (!i || !i.variablesReference) {
    e.innerDiv.classList.add("hideExpander");
  } else {
    e.innerDiv.classList.remove("hideExpander");
  }
  if (!e.isCollapsed) {
    watchPanel.expandedCache[e.getFullPath()] = true;
  } else {
    delete watchPanel.expandedCache[e.getFullPath()];
  }
  if (i) {
    o.innerText = i.result;
    n.innerText = i.type;
    if (!e.isCollapsed) {
      if (!e.queried) {
        e.queried = true;
        debugSocket.request(
          "variables",
          { variablesReference: i.variablesReference },
          (t) => {
            variablesPanel.syncVariablesToNode(t, e);
          }
        );
      }
    }
  } else {
    if (e.queried) {
      e.clear();
      e.queried = false;
    }
    t.innerText = e.name + ":";
    o.innerText = "not available";
  }
}
function watchRenderNode(e) {
  var t = createDOMElement(e.innerDiv, "div", "variableName");
  var o = createDOMElement(e.innerDiv, "div", "variableValue");
  var n = createDOMElement(e.innerDiv, "div", "variableType");
  var i = e.customRenderData;
  t.innerText = i.name + ":";
  o.innerText = i.value;
  n.innerText = i.type;
}
class _WatchPanel {
  constructor(e, t, o, n, i, r) {
    this.expandedCache = {};
    this.tree = new treeView(e, "监视", "watches:", false, 5, false);
    this.tree.render();
    this.selectedEditorNode = undefined;
    this.tree.showFolderIcons = false;
    this.tree.showItemIcons = false;
    this.tree.onDblClickItem = onWatchDblClick;
    this.tree.onDblClick = watches_onTreeDblClick;
    this.tree.onDeleteKey = onDeleteKey;
    this.tree.emptyFolderText = "";
    this.tree.needsFlexNodes = true;
    var s = createDOMElement(
      this.tree.sectionHeader,
      "div",
      "panelHeaderIcon plusIcon"
    );
    s.onclick = watches_onTreeDblClick;
    var a = createDOMElement(
      this.tree.sectionHeader,
      "div",
      "panelHeaderIcon clearScreenIcon"
    );
    a.onclick = (e) => {
      this.clearWatches();
      e.stopPropagation();
    };
  }
  getWatches() {
    return Object.keys(this.tree.rootFolder.entries);
  }
  evaluateWatch(e) {
    var t = this.tree.rootFolder.entries[e];
    if (!activeDebuggingFrameId) {
      t.customRenderData = undefined;
      if (t.clear) t.clear();
      t.queried = false;
      t.render();
      return;
    }
    debugSocket.request(
      "evaluate",
      { expression: e, context: "watch", frameId: activeDebuggingFrameId },
      (e) => {
        if (e.success) {
          t.customRenderData = e.body;
        } else {
          t.customRenderData = { result: e.message, type: "ERROR" };
        }
        if (t.clear) t.clear();
        t.queried = false;
        t.render();
      }
    );
  }
  evaluateWatches() {
    var e = Object.keys(this.tree.rootFolder.entries);
    e.forEach((e) => {
      this.evaluateWatch(e);
    });
  }
  clearWatchResults() {
    var e = Object.keys(this.tree.rootFolder.entries);
    e.forEach((e) => {
      var t = this.tree.rootFolder.entries[e];
      t.customRenderData = undefined;
      if (t.clear) t.clear();
      t.queried = false;
      t.render();
    });
  }
  clearWatches() {
    this.tree.clear();
  }
}
function createWatchPanel(e) {
  if (watchPanel) return watchPanel;
  watchPanel = new _WatchPanel(e);
}
class webSocket {
  constructor(e, t) {
    this.url = e;
    this.handler = t;
    this.requestsAwaitingResponse = {};
    this.requestId = 0;
    this.socket = createWebsocketWithFallback(e);
    this.socket.binaryType = "arraybuffer";
    this.socket.onopen = (e) => {
      connectionStateChanged();
      this.handler.onConnected();
    };
    this.socket.onmessage = (e) => {
      const t = new DataView(e.data);
      const o = t.getInt32(0, true);
      const n = t.getInt32(4, true);
      const i = e.data.slice(8);
      if (o === -1) {
        this.handler.onNotification(n, i);
      } else {
        var r = this.requestsAwaitingResponse[o];
        if (r) {
          delete this.requestsAwaitingResponse[o];
          r(n, i);
        }
      }
    };
    this.socket.onclose = connectionStateChanged;
    this.socket.onerror = (e) => {
      this.hasErrored = true;
      connectionStateChanged();
      this.socket.close();
    };
  }
  request0(e, t) {
    var o = this.requestId++;
    var n;
    const i = 5;
    n = new Uint8Array([
      e,
      o & 255,
      (o >> 8) & 255,
      (o >> 16) & 255,
      (o >> 24) & 255,
    ]);
    if (t) this.requestsAwaitingResponse[o] = t;
    this.socket.send(n);
  }
  request1(e, t, o) {
    var n = this.requestId++;
    if (typeof t === "string") {
      t = new TextEncoder().encode(t);
    }
    var i;
    const r = 5;
    i = new Uint8Array(r + t.length);
    i.set([e, n & 255, (n >> 8) & 255, (n >> 16) & 255, (n >> 24) & 255], 0);
    i.set(t, r);
    if (o) this.requestsAwaitingResponse[n] = o;
    this.socket.send(i);
  }
  request1a(e, t, o, n) {
    var i = this.requestId++;
    if (typeof o === "string") {
      o = new TextEncoder().encode(o);
    }
    var r;
    const s = 9;
    r = new Uint8Array(s + o.length);
    r.set(
      [
        e,
        i & 255,
        (i >> 8) & 255,
        (i >> 16) & 255,
        (i >> 24) & 255,
        t & 255,
        (t >> 8) & 255,
        (t >> 16) & 255,
        (t >> 24) & 255,
      ],
      0
    );
    r.set(o, s);
    if (n) this.requestsAwaitingResponse[i] = n;
    this.socket.send(r);
  }
  request2(e, t, o, n) {
    var i = this.requestId++;
    if (typeof t === "string") {
      t = new TextEncoder().encode(t);
    }
    if (typeof o === "string") {
      o = new TextEncoder().encode(o);
    }
    var r;
    const s = 9;
    r = new Uint8Array(s + t.length + o.length);
    r.set(
      [
        e,
        i & 255,
        (i >> 8) & 255,
        (i >> 16) & 255,
        (i >> 24) & 255,
        t.length & 255,
        (t.length >> 8) & 255,
        (t.length >> 16) & 255,
        (t.length >> 24) & 255,
      ],
      0
    );
    r.set(t, s);
    r.set(o, s + t.length);
    if (n) this.requestsAwaitingResponse[i] = n;
    this.socket.send(r);
  }
  request2a(e, t, o, n, i, r) {
    var s = this.requestId++;
    if (typeof n === "string") {
      n = new TextEncoder().encode(n);
    }
    if (typeof i === "string") {
      i = new TextEncoder().encode(i);
    }
    if (t == undefined) t = 0;
    if (o == undefined) o = 0;
    var a;
    const l = 17;
    a = new Uint8Array(l + n.length + i.length);
    a.set(
      [
        e,
        s & 255,
        (s >> 8) & 255,
        (s >> 16) & 255,
        (s >> 24) & 255,
        t & 255,
        (t >> 8) & 255,
        (t >> 16) & 255,
        (t >> 24) & 255,
        o & 255,
        (o >> 8) & 255,
        (o >> 16) & 255,
        (o >> 24) & 255,
        n.length & 255,
        (n.length >> 8) & 255,
        (n.length >> 16) & 255,
        (n.length >> 24) & 255,
      ],
      0
    );
    a.set(n, l);
    a.set(i, l + n.length);
    if (r) this.requestsAwaitingResponse[s] = r;
    this.socket.send(a);
  }
}
class webSocketJson {
  constructor(e, t) {
    this.url = e;
    this.handler = t;
    this.socket = createWebsocketWithFallback(e);
    this.socket.binaryType = "arraybuffer";
    this.socket.onopen = (e) => {
      connectionStateChanged();
      this.handler.onConnected();
    };
    this.socket.onmessage = (e) => {
      var t;
      if (e.data.byteLength > 4) {
        var o = new Int32Array(e.data, 0, 1);
        if (o[0] === -1381654) {
          var n = 4;
          while (n < e.data.byteLength) {
            var i = new DataView(e.data, n, 4);
            var r = i.getInt32(0, true);
            n += 4;
            var s = new DataView(e.data, n, r);
            n += r;
            try {
              let e = new TextDecoder().decode(s);
              t = JSON.parse(e);
            } catch (t) {
              debugger;
              alertWithClipboardText(
                "webSocketJson: bad json received",
                new TextDecoder().decode(e.data)
              );
              return;
            }
            t.transferSize = r;
            this.handler.onReceivedObject(t);
          }
          return;
        }
      }
      try {
        let o = new TextDecoder().decode(e.data);
        t = JSON.parse(o);
      } catch (t) {
        debugger;
        alertWithClipboardText(
          "webSocketJson: bad json received",
          new TextDecoder().decode(e.data)
        );
        return;
      }
      t.transferSize = e.data.byteLength;
      this.handler.onReceivedObject(t);
    };
    this.socket.onclose = connectionStateChanged;
    this.socket.onerror = (e) => {
      this.hasErrored = true;
      connectionStateChanged();
      this.socket.close();
    };
  }
  sendObject(e) {
    this.socket.send(JSON.stringify(e));
  }
}
var buildConfigSelector;
function getTransparentPngFromBitmapWithKeyColor(e, t) {
  var o = document.getElementById("theCanvas");
  var n = o.getContext("2d");
  var i = new Image();
  i.onload = function () {
    n.imageSmoothingEnabled = false;
    var e = i.width;
    var r = i.height;
    o.width = e;
    o.height = r;
    o.style.width = e + "px";
    o.style.height = r + "px";
    n.drawImage(i, 0, 0, e, r);
    var s = n.getImageData(0, 0, e, r);
    var a = (r - 1) * (e * 4);
    var l = s.data[a];
    var d = s.data[a + 1];
    var c = s.data[a + 2];
    for (var u = 0; u < s.data.length; u += 4) {
      if (s.data[u] == l && s.data[u + 1] == d && s.data[u + 2] == c) {
        s.data[u + 3] = 0;
      }
    }
    n.clearRect(0, 0, e, r);
    n.putImageData(s, 0, 0);
    var p = o.toDataURL();
    t(p);
  };
  i.src = e;
}
var tbVersionInfo = "IDE BETA 423";
function createVirtualListView(e) {
  var t = createScrollableContainer(e);
  var o = t.contentDiv;
  o.itemCount = 0;
  var n = document.createElement("div");
  n.style.top = "0";
  n.style.width = "100%";
  n.style.height = "100%";
  n.style.position = "sticky";
  o.appendChild(n);
  var i = document.createElement("div");
  i.style.width = "100%";
  i.style.height = "100%";
  i.style.position = "absolute";
  n.appendChild(i);
  o.rowsContainer = i;
  var r = [];
  var s = [];
  var a = [];
  var l = document.createElement("div");
  l.style.width = "fit-content";
  l.style.minWidth = "-webkit-fill-available";
  l.style.display = "none";
  l.className = "listitem";
  l.listview = i;
  i.appendChild(l);
  var d = false;
  var c = false;
  o.onAsyncGetItemHTML = (e) => e;
  o.getCachedDomNode = (e) => {
    if (e >= r.length) {
      let e = document.createElement("div");
      e.style.width = "fit-content";
      e.style.minWidth = "-webkit-fill-available";
      e.className = "listitem";
      e.listview = o;
      e.onclick = (t) => {
        if (o.onClickItem) o.onClickItem({ index: e.index });
      };
      e.ondblclick = (t) => {
        if (o.onDblClickItem) o.onDblClickItem({ index: e.index });
      };
      r.push(e);
      return e;
    } else {
      return r[e];
    }
  };
  o.prepareDomNode = async (e, t) => {
    e.index = t;
    e.style.maxHeight = "";
    if (o.noCache) {
      e.innerHTML = await o.onAsyncGetItemHTML(t);
      a[t] = e.offsetHeight;
    } else {
      if (s[t]) {
        e.innerHTML = s[t];
      } else {
        e.innerHTML = await o.onAsyncGetItemHTML(t);
        s[t] = e.innerHTML;
        a[t] = e.offsetHeight;
      }
    }
    e.style.maxHeight = e.offsetHeight;
  };
  o.getCachedHeight = async (e) => {
    if (a[e] !== undefined) {
      return a[e];
    } else {
      var t = await o.onAsyncGetItemHTML(e);
      l.style.display = "block";
      l.innerHTML = t;
      if (!o.noCache) {
        s[e] = t;
      }
      var n = l.offsetHeight;
      a[e] = n;
      l.style.display = "none";
      return n;
    }
  };
  o.updateScrollRange = async () => {
    if (o.offsetHeight === 0) return;
    if (o.scrollrangeTimer) {
      clearTimeout(o.scrollrangeTimer);
      o.scrollrangeTimer = undefined;
    }
    var e = o.itemCount - 1;
    var n = i.clientHeight;
    var r = 0;
    var s = 1;
    while (e !== -1) {
      s = await o.getCachedHeight(e);
      r += s;
      e--;
      if (r >= n) {
        break;
      }
    }
    o.finalPageFullHeight = r;
    o.finalPageOverspillPixels = r > n ? r - n : 0;
    o.finalPageOverspillPercent = s
      ? Math.floor((o.finalPageOverspillPixels * 100) / s)
      : 0;
    o.finalPageVisibleItemsCount = o.itemCount - 1 - e;
    var a =
      (o.itemCount - o.finalPageVisibleItemsCount) * 100 +
      o.finalPageOverspillPercent;
    t.setScrollRangeY(a / 100, o.finalPageVisibleItemsCount);
    if (o.autoScroll) {
      if (o.invertMode) {
        t.setScrollY(0);
      } else {
        t.setScrollY(a);
      }
    } else {
      t.resyncScrollY();
    }
  };
  o.repaint = async () => {
    if (o.offsetHeight === 0) return;
    if (d) {
      c = true;
      return;
    }
    d = true;
    if (o.repaintTimer) {
      clearTimeout(o.repaintTimer);
      o.repaintTimer = undefined;
    }
    i.innerHTML = "";
    i.appendChild(l);
    await o.updateScrollRange();
    var e = t.scrollValueY * 100;
    var n = Math.floor(e / 100);
    var r = e % 100;
    var s = n;
    var a = i.clientHeight;
    var u = 0;
    var p = undefined;
    var f = 0;
    var g = 0;
    var m = 0;
    if (s >= o.itemCount) {
      s = o.itemCount - 1;
      r = 99;
    }
    if (o.itemCount) {
      while (1) {
        let e = o.getCachedDomNode(f);
        i.appendChild(e);
        var h = s;
        if (o.invertMode) {
          h = o.itemCount - 1 - s;
        }
        await o.prepareDomNode(e, h);
        if (e.clientWidth > m) m = e.clientWidth;
        g = e.offsetHeight;
        u += g;
        if (p === undefined) {
          p = -((g * r) / 100);
        }
        s++;
        f++;
        if (o.invertMode) {
          if (s == 1) {
            if (o.autoScroll == false && o.autoScrollAutoLock) {
              o.autoScroll = true;
              if (o.onautoscrollchanged) o.onautoscrollchanged({});
              i.innerHTML = "";
              d = false;
              await o.repaint();
              return;
            }
          }
          if (s >= o.itemCount) {
            break;
          }
        } else {
          if (s >= o.itemCount) {
            if (o.autoScroll) {
              break;
            }
            if (o.autoScrollAutoLock) {
              o.autoScroll = true;
              if (o.onautoscrollchanged) o.onautoscrollchanged({});
              i.innerHTML = "";
              d = false;
              await o.repaint();
              return;
            }
            if (f == 1) {
              if (g <= a) {
                p = 0;
              } else {
                var v = g - a;
                p = -((v * r) / 100);
              }
            }
            break;
          }
        }
        if (u + p > a) break;
      }
    }
    t.setScrollRangeX(m - o.offsetWidth);
    i.style.top = (p ? p : 0) + "px";
    o.visibleTop = n;
    o.visibleCount = f - 1;
    o.fullyVisibleCount = o.visibleCount;
    if (u + p > a) o.fullyVisibleCount--;
    t.setScrollPageSizeX(o.offsetWidth);
    t.setScrollPageSizeY(o.visibleCount);
    o.lastAutoScrollRenderedScrollTop = t.scrollValueY;
    if (o.visibleTop === 0 && o.fullyVisibleCount + 1 == o.itemCount) {
      if (o.onHeightTooLarge) o.onHeightTooLarge(u);
    }
    d = false;
    if (c) {
      c = false;
      o.repaint();
    }
    if (o.onFinishedRender) o.onFinishedRender();
  };
  o.onwheel = (e) => {
    if ((!o.invertMode && e.deltaY < 0) || (o.invertMode && e.deltaY > 0)) {
      if (o.autoScroll) {
        if (o.autoScrollAutoUnlock) {
          o.autoScroll = false;
          if (o.onautoscrollchanged) o.onautoscrollchanged({});
        }
      }
    }
  };
  t.onResized = async (e) => {
    await o.repaint();
  };
  t.onscrollY = async (e) => {
    if (o.autoScroll) {
      if (t.scrollValueY != o.lastAutoScrollRenderedScrollTop) {
        if (o.autoScrollAutoUnlock) {
          o.autoScroll = false;
          if (o.onautoscrollchanged) o.onautoscrollchanged({});
        } else {
          t.setScrollY(o.lastAutoScrollRenderedScrollTop);
        }
      } else {
        return;
      }
    }
    await o.repaint();
  };
  t.onscrollX = (e) => {
    i.style.left = -t.scrollValueX + "px";
  };
  o.setTop = (e) => {
    t.scrollValueY = e;
    o.repaint();
  };
  o.notifyChangedItem = (e) => {
    if (!o.noCache) delete s[e];
    delete a[e];
    if (e >= o.visibleTop && e <= o.visibleTop + o.visibleCount) {
      o.repaintSoon();
    } else {
      o.updateScrollRangeSoon();
    }
  };
  o.ensureVisible = (e) => {
    if (e < o.visibleTop) {
      o.setTop(e);
    } else if (o.fullyVisibleCount === -1) {
    } else if (e > o.visibleTop + o.fullyVisibleCount) {
      let t = e - o.fullyVisibleCount;
      if (t < 0) o.visibleTop = 0;
      o.setTop(t);
    }
  };
  o.setItemCount = (e, t) => {
    var n = o.itemCount;
    var i = o.visibleTop + o.visibleCount;
    var r = false;
    if (o.invertMode) {
      r = o.visibleTop == 0;
      t = true;
    } else {
      r = i >= n - 1;
    }
    o.itemCount = e;
    if (o.itemCount <= i || r) {
      t = true;
    } else {
    }
    if (t) {
      o.repaintSoon();
    } else {
      o.updateScrollRangeSoon();
    }
    while (n > e) {
      n--;
      if (!o.noCache) delete s[n];
      delete a[n];
    }
  };
  o.resetScrollPosition = () => {
    t.scrollValueX = 0;
    t.scrollValueY = 0;
    i.style.left = "0";
    i.style.top = "0";
  };
  o.setAutoScroll = (e) => {
    o.autoScroll = e;
    if (o.onautoscrollchanged) o.onautoscrollchanged({});
  };
  o.setInvertMode = (e) => {
    o.invertMode = e;
    o.repaint();
  };
  o.setShowScrollbarH = (e) => {
    t.setShowScrollbarH(e);
  };
  o.setShowScrollbarV = (e) => {
    t.setShowScrollbarV(e);
  };
  o.setAutoScrollAutoLock = (e) => {
    o.autoScrollAutoLock = e;
  };
  o.setAutoScrollAutoUnlock = (e) => {
    o.autoScrollAutoUnlock = e;
  };
  o.repaintSoon = () => {
    if (o.repaintTimer) return;
    o.repaintTimer = setTimeout(() => {
      o.repaintTimer = undefined;
      o.repaint();
    }, 100);
  };
  o.updateScrollRangeSoon = () => {
    if (o.scrollrangeTimer) return;
    o.scrollrangeTimer = setTimeout(() => {
      o.scrollrangeTimer = undefined;
      o.updateScrollRange();
    }, 100);
  };
  return o;
}
function createListView(e) {
  var t = createVirtualListView(e);
  t.invertMode = false;
  t.noCache = true;
  t.dataNodes = [];
  t.dataNodesDATA = [];
  t.onAsyncGetItemHTML = (e) => t.dataNodes[e];
  t.getItem = (e) => t.dataNodes[e];
  t.getItemData = (e) => t.dataNodesDATA[e];
  t.updateItem = (e, o) => {
    if (o !== undefined) t.dataNodes[e] = o.toString();
    t.notifyChangedItem(e);
  };
  t.addItem = (e, o) => {
    var n = t.itemCount;
    if (e !== undefined) t.dataNodes[n] = e.toString();
    if (o !== undefined) t.dataNodesDATA[n] = o;
    t.setItemCount(n + 1);
    return n;
  };
  t.removeItem = (e) => {
    t.dataNodes.splice(e, 1);
    t.dataNodesDATA.splice(e, 1);
    var o = false;
    var n = t.visibleTop + t.visibleCount;
    if (e <= n) {
      o = true;
    } else {
    }
    t.setItemCount(t.itemCount - 1, o);
  };
  t.clear = () => {
    t.dataNodes = [];
    t.dataNodesDATA = [];
    t.itemCount = 0;
    t.cachedHeights = [];
    t.repaint();
  };
  return t;
}
function createScrollableContainer(e) {
  new ResizeObserver(() => {
    cachedHeights = [];
    if (e.onResized) e.onResized();
  }).observe(e);
  e.scrollValueX = 0;
  e.scrollValueY = 0;
  e.showScrollbarV = "auto";
  e.showScrollbarH = "auto";
  e.setShowScrollbarV = (t) => {
    e.showScrollbarV = t;
    if (t !== "auto") {
      n.style.display = t ? "block" : "none";
      o.style.width = t ? "calc(100% - 16px)" : "100%";
      p.style.width = t ? "calc(100% - 16px)" : "100%";
    }
  };
  e.setShowScrollbarH = (t) => {
    e.showScrollbarH = t;
    if (t !== "auto") {
      p.style.display = t ? "block" : "none";
      o.style.height = t ? "calc(100% - 16px)" : "100%";
      n.style.height = t ? "calc(100% - 16px)" : "100%";
    }
  };
  e.setScrollPageSizeX = (t) => {
    e.scrollPageSizeX = t;
  };
  e.setScrollPageSizeY = (t) => {
    e.scrollPageSizeY = t;
  };
  e.setScrollRangeY = (t, i) => {
    if (t == 0) {
      a.style.visibility = "hidden";
      a.style.display = "none";
    } else {
      a.style.visibility = "visible";
      a.style.display = "block";
    }
    if (e.showScrollbarV === "auto") {
      n.style.display = t ? "block" : "none";
      o.style.width = t ? "calc(100% - 16px)" : "100%";
      p.style.width = t ? "calc(100% - 16px)" : "100%";
    }
    if (!i) i = 1;
    const r = 4;
    var l = s.offsetHeight - r;
    a.style.height = t ? Math.min(Math.max(1e3 / (t + i), 24), l - 1) : "100%";
    e.scrollTrackbarVisibleY = l - a.offsetHeight;
    e.scrollMaxY = t;
  };
  e.setScrollYTrack = (t) => {
    e.setScrollY((t / e.scrollTrackbarVisibleY) * e.scrollMaxY);
  };
  e.setScrollY = (t) => {
    if (t < 0) t = 0;
    if (t > e.scrollMaxY) t = e.scrollMaxY;
    if (e.scrollValueY === t) return;
    e.scrollValueY = t;
    t = Math.floor((t / e.scrollMaxY) * e.scrollTrackbarVisibleY);
    a.style.top = t + "px";
    if (e.onscrollY) e.onscrollY();
  };
  e.resyncScrollY = () => {
    if (e.scrollValueY > e.scrollMaxY) e.scrollValueY = e.scrollMaxY;
    var t = e.scrollValueY;
    t = Math.floor((t / e.scrollMaxY) * e.scrollTrackbarVisibleY);
    a.style.top = t + "px";
  };
  e.setScrollRangeX = (t) => {
    if (t == 0) {
      h.style.visibility = "hidden";
      h.style.display = "none";
    } else {
      h.style.visibility = "visible";
      h.style.display = "block";
    }
    if (e.showScrollbarH === "auto") {
      p.style.display = t ? "block" : "none";
      o.style.height = t ? "calc(100% - 16px)" : "100%";
      n.style.height = t ? "calc(100% - 16px)" : "100%";
    }
    const i = 4;
    var r = m.offsetWidth - i;
    h.style.width = t ? Math.min(Math.max(1e3 / (t + 4), 24), r - 1) : "100%";
    e.scrollTrackbarVisibleX = r - h.offsetWidth;
    e.scrollMaxX = t;
  };
  e.setScrollXTrack = (t) => {
    e.setScrollX((t / e.scrollTrackbarVisibleX) * e.scrollMaxX);
  };
  e.setScrollX = (t) => {
    if (t < 0) t = 0;
    if (t > e.scrollMaxX) t = e.scrollMaxX;
    if (e.scrollValueX === t) return;
    e.scrollValueX = t;
    t = Math.floor((t / e.scrollMaxX) * e.scrollTrackbarVisibleX);
    h.style.left = t + "px";
    if (e.onscrollX) e.onscrollX();
  };
  e.scrollDeltaX = (t) => {
    e.setScrollX(e.scrollValueX + t);
  };
  e.scrollDeltaY = (t) => {
    e.setScrollY(e.scrollValueY + t);
  };
  var t = "#959494";
  var o = document.createElement("div");
  o.className = "listItems";
  o.style.height = "calc(100% - 16px)";
  o.style.width = "calc(100% - 16px)";
  o.style.overflow = "hidden";
  e.appendChild(o);
  e.contentDiv = o;
  e.onwheel = (t) => {
    t.preventDefault();
    if (t.deltaX) {
      e.scrollDeltaX(t.deltaX / 70);
    }
    if (t.deltaY) {
      e.scrollDeltaY(t.deltaY / 70);
    }
  };
  var n = document.createElement("div");
  n.style.height = "calc(100% - 16px)";
  n.style.width = "16px";
  n.style.top = "0px";
  n.style.right = "0px";
  n.style.position = "absolute";
  n.style.background = "rgba(128, 128, 128, 0.12)";
  n.style.boxSizing = "border-box";
  e.appendChild(n);
  n.onmousedown = (t) => {
    var o = 0;
    if (t.offsetY > a.offsetTop - i.offsetHeight + a.offsetHeight / 2) {
      o = e.scrollPageSizeY;
    } else {
      o = -e.scrollPageSizeY;
    }
    var r = undefined;
    var s = setTimeout(() => {
      s = undefined;
      a.style.transition = "top 0.15s ease-out 0s";
      r = setInterval(() => {
        e.scrollDeltaY(o);
        var n = parseInt(a.style.top);
        var i = false;
        if (t.offsetY > n + a.offsetHeight / 2) {
          if (o != e.scrollPageSizeY) {
            i = true;
          }
        } else {
          if (o != -e.scrollPageSizeY) {
            i = true;
          }
        }
        if (i) {
          e.setScrollYTrack(t.offsetY - a.offsetHeight / 2);
          clearInterval(r);
          r = undefined;
        }
      }, 150);
    }, 300);
    n.onmouseup = (t) => {
      setTimeout(() => {
        a.style.transition = "none";
      }, 150);
      if (s) {
        clearTimeout(s);
        e.scrollDeltaY(o);
      }
      if (r) clearInterval(r);
      n.onmouseup = undefined;
    };
    t.preventDefault();
    t.stopPropagation();
    return false;
  };
  var i = document.createElement("div");
  i.style.height = "16px";
  i.style.width = "16px";
  i.style.paddingLeft = "5px";
  i.style.paddingTop = "5px";
  i.style.boxSizing = "border-box";
  n.appendChild(i);
  i.onclick = (e) => {
    e.preventDefault();
    e.stopPropagation();
    return false;
  };
  i.onmousedown = (t) => {
    var o = undefined;
    var n = setTimeout(() => {
      n = undefined;
      a.style.transition = "top 0.5s ease-out 0s";
      o = setInterval(() => {
        e.scrollDeltaY(-1);
      }, 70);
    }, 300);
    i.onmouseup = (t) => {
      if (n) {
        clearTimeout(n);
        e.scrollDeltaY(-1);
      } else {
        setTimeout(() => {
          a.style.transition = "none";
        }, 500);
      }
      if (o) clearInterval(o);
      i.onmouseup = undefined;
    };
    t.preventDefault();
    t.stopPropagation();
    return false;
  };
  var r = document.createElement("div");
  r.className = "triangle";
  r.style.background = t;
  i.appendChild(r);
  var s = document.createElement("div");
  s.style.height = "calc(100% - 32px)";
  s.style.width = "16px";
  s.style.padding = "2px";
  s.style.boxSizing = "border-box";
  n.appendChild(s);
  var a = document.createElement("div");
  a.style.height = "100%";
  a.style.top = "0px";
  a.style.position = "relative";
  a.style.width = "12px";
  a.style.borderRadius = "10px";
  a.style.background = t;
  a.style.boxSizing = "border-box";
  s.appendChild(a);
  var l = undefined;
  var d = undefined;
  a.onpointerdown = (t) => {
    l = Math.floor(a.offsetTop) - 16;
    a.setPointerCapture(t.pointerId);
    a.onpointermove = (t) => {
      if (d === undefined) d = t.screenY;
      var o = Math.floor(t.screenY - d);
      e.setScrollYTrack(l + o);
    };
    a.onpointerup = (e) => {
      a.onpointermove(e);
      a.releasePointerCapture(e.pointerId);
      a.onpointermove = undefined;
      a.onpointerup = undefined;
      d = undefined;
    };
    a.onpointermove(t);
  };
  a.onmousedown = (e) => {
    e.preventDefault();
    e.stopPropagation();
    return false;
  };
  a.onclick = (e) => {
    e.preventDefault();
    e.stopPropagation();
    return false;
  };
  var c = document.createElement("div");
  c.style.height = "16px";
  c.style.width = "16px";
  c.style.paddingLeft = "6px";
  c.style.paddingTop = "3px";
  c.style.boxSizing = "border-box";
  n.appendChild(c);
  c.onclick = (e) => {
    e.preventDefault();
    e.stopPropagation();
    return false;
  };
  c.onmousedown = (t) => {
    var o = undefined;
    var n = setTimeout(() => {
      n = undefined;
      a.style.transition = "top 0.5s ease-out 0s";
      o = setInterval(() => {
        e.scrollDeltaY(1);
      }, 70);
    }, 300);
    c.onmouseup = (t) => {
      if (n) {
        clearTimeout(n);
        e.scrollDeltaY(1);
      } else {
        setTimeout(() => {
          a.style.transition = "none";
        }, 500);
      }
      if (o) clearInterval(o);
      c.onmouseup = undefined;
    };
    t.preventDefault();
    t.stopPropagation();
    return false;
  };
  var u = document.createElement("div");
  u.className = "triangle triangleDown";
  u.style.background = t;
  c.appendChild(u);
  var p = document.createElement("div");
  p.style.height = "16px";
  p.style.width = "calc(100% - 16px)";
  p.style.bottom = "0px";
  p.style.position = "absolute";
  p.style.background = "rgba(128, 128, 128, 0.12)";
  p.style.boxSizing = "border-box";
  e.appendChild(p);
  p.onmousedown = (t) => {
    var o = 0;
    if (t.offsetX > h.offsetLeft - i.offsetHeight + h.offsetHeight / 2) {
      o = e.scrollPageSizeX;
    } else {
      o = -e.scrollPageSizeX;
    }
    var n = undefined;
    var r = setTimeout(() => {
      r = undefined;
      h.style.transition = "left 0.15s ease-out 0s";
      n = setInterval(() => {
        e.scrollDeltaX(o);
        var i = parseInt(h.style.left);
        var r = false;
        if (t.offsetX > i + h.offsetWidth / 2) {
          if (o != e.scrollPageSizeX) {
            r = true;
          }
        } else {
          if (o != -e.scrollPageSizeX) {
            r = true;
          }
        }
        if (r) {
          e.setScrollXTrack(t.offsetX - h.offsetWidth / 2);
          clearInterval(n);
          n = undefined;
        }
      }, 150);
    }, 300);
    p.onmouseup = (t) => {
      setTimeout(() => {
        h.style.transition = "none";
      }, 150);
      if (r) {
        clearTimeout(r);
        e.scrollDeltaX(o);
      }
      if (n) clearInterval(n);
      p.onmouseup = undefined;
    };
    t.preventDefault();
    t.stopPropagation();
    return false;
  };
  var f = document.createElement("div");
  f.style.height = "16px";
  f.style.width = "16px";
  f.style.paddingLeft = "6px";
  f.style.paddingTop = "6px";
  f.style.display = "inline-block";
  f.style.boxSizing = "border-box";
  p.appendChild(f);
  f.onclick = (e) => {
    e.preventDefault();
    e.stopPropagation();
    return false;
  };
  f.onmousedown = (t) => {
    var o = undefined;
    var n = setTimeout(() => {
      n = undefined;
      h.style.transition = "left 0.5s ease-out 0s";
      o = setInterval(() => {
        e.scrollDeltaX(-1);
      }, 70);
    }, 300);
    f.onmouseup = (t) => {
      if (n) {
        clearTimeout(n);
        e.scrollDeltaX(-1);
      } else {
        setTimeout(() => {
          h.style.transition = "none";
        }, 500);
      }
      if (o) clearInterval(o);
      f.onmouseup = undefined;
    };
    t.preventDefault();
    t.stopPropagation();
    return false;
  };
  var g = document.createElement("div");
  g.className = "triangle triangleLeft";
  g.style.background = t;
  f.appendChild(g);
  var m = document.createElement("div");
  m.style.height = "16px";
  m.style.width = "calc(100% - 32px)";
  m.style.padding = "2px";
  m.style.display = "inline-block";
  m.style.boxSizing = "border-box";
  p.appendChild(m);
  var h = document.createElement("div");
  h.style.width = "100%";
  h.style.left = "0px";
  h.style.position = "relative";
  h.style.height = "12px";
  h.style.borderRadius = "10px";
  h.style.background = t;
  h.style.boxSizing = "border-box";
  m.appendChild(h);
  var v = undefined;
  var y = undefined;
  h.onpointerdown = (t) => {
    v = Math.floor(h.offsetLeft) - 16;
    h.setPointerCapture(t.pointerId);
    h.onpointermove = (t) => {
      if (y === undefined) y = t.screenX;
      var o = Math.floor(t.screenX - y);
      e.setScrollXTrack(v + o);
    };
    h.onpointerup = (e) => {
      h.onpointermove(e);
      h.releasePointerCapture(e.pointerId);
      h.onpointermove = undefined;
      h.onpointerup = undefined;
      y = undefined;
    };
    h.onpointermove(t);
  };
  h.onmousedown = (e) => {
    e.preventDefault();
    e.stopPropagation();
    return false;
  };
  h.onclick = (e) => {
    e.preventDefault();
    e.stopPropagation();
    return false;
  };
  var b = document.createElement("div");
  b.style.height = "16px";
  b.style.width = "16px";
  b.style.paddingLeft = "6px";
  b.style.paddingTop = "5px";
  b.style.display = "inline-block";
  b.style.boxSizing = "border-box";
  p.appendChild(b);
  b.onclick = (e) => {
    e.preventDefault();
    e.stopPropagation();
    return false;
  };
  b.onmousedown = (t) => {
    var o = undefined;
    var n = setTimeout(() => {
      n = undefined;
      h.style.transition = "left 0.5s ease-out 0s";
      o = setInterval(() => {
        e.scrollDeltaX(1);
      }, 70);
    }, 300);
    b.onmouseup = (t) => {
      if (n) {
        clearTimeout(n);
        e.scrollDeltaX(1);
      } else {
        setTimeout(() => {
          h.style.transition = "none";
        }, 500);
      }
      if (o) clearInterval(o);
      b.onmouseup = undefined;
    };
    t.preventDefault();
    t.stopPropagation();
    return false;
  };
  var C = document.createElement("div");
  C.className = "triangle triangleRight";
  C.style.background = t;
  b.appendChild(C);
  return e;
}
initMonaco();
window.onload = () => {
  initHostAppObject(() => {
    initMisc();
    initConnectionManager();
    initRootConnection();
    initKeyboardShortcuts();
    initContextMenu();
    initTooltips();
    initTopLevelMenus();
    initMsgBox();
    initDialog();
    initLayout(() => {
      initPanels();
      initOpenEditorsPanel();
      initDebugConsolePanel();
      initOutlinesPanel();
      initProblemsPanel();
      initCallStackPanel();
      initVariablesPanel();
      initWatchPanel();
      initFormDesigners();
      restorePanelsConfiguration();
      initDebugSocket();
      initLspSocket();
      unfreezeLayoutChanges();
      buildConfigSelector = document.getElementById("buildConfigSelector");
      buildConfigSelector.options.add(
        createDOMElement(undefined, "option", "", "win32")
      );
      buildConfigSelector.options.add(
        createDOMElement(undefined, "option", "", "win64")
      );
      var e = createDOMElement(
        undefined,
        "option",
        "",
        "SafeMode [filesystem only]"
      );
      e.value = "nocompile";
      buildConfigSelector.options.add(e);
      buildConfigSelector.onchange = changedActiveBuildConfig;
      loadIDEOptions(() => parseCommandLine());
      loadPublisherInfo();
      setTimeout(() => {
        changedSize();
      }, 0);
      HostForceFocus();
    });
  });
};
function parseCommandLine() {
  getIDECommandLineArgs((e) => {
    var t = false;
    var o = "";
    var n = [];
    var i = e.split(" ");
    i.forEach((e) => {
      if (t) {
        if (e.substring(e.length - 1, e.length) == '"') {
          t = false;
          o += " " + e.substring(0, e.length - 1);
          n.push(o);
        } else {
          o += " " + e;
        }
      } else {
        if (e.substring(0, 1) == '"') {
          if (e.length > 1 && e.substring(e.length - 1, e.length) == '"') {
            n.push(e.substring(1, e.length - 1));
          } else {
            t = true;
            o = e.substring(1);
          }
        } else {
          n.push(e.trim());
        }
      }
    });
    var r = 0;
    var s = undefined;
    var a = false;
    while (r < n.length) {
      var l = n[r];
      if (l.substring(0, 2) == "--") {
      } else {
        if (s) a = true;
        s = l;
      }
      r++;
    }
    prepareToStart();
    if (a) {
      alert("错误的命令行语法。");
      showFrontPageDialog();
    } else {
      if (s) {
        root.loadProject(s);
      } else {
        showFrontPageDialog();
      }
    }
  });
}
function changedActiveBuildConfig() {
  if (!compilerPassKey) return;
  restartCompilerSafely();
}
